import uuid
from typing import TYPE_CHECKING

from sqlalchemy import Boolean, ForeignKey, JSON, String, Text
from sqlalchemy import Uuid as UUID
from sqlalchemy.orm import Mapped, mapped_column, relationship

from src.models.base import Base, TimestampMixin, UUIDPrimaryKeyMixin
from src.models.tool.tool_definition_manifest import ToolDefinitionManifest

if TYPE_CHECKING:
    from src.models.user import User


class ToolType(UUIDPrimaryKeyMixin, TimestampMixin, Base):
    __tablename__ = "tool_types"

    name: Mapped[str] = mapped_column(String(255), unique=True, nullable=False)
    display_name: Mapped[str] = mapped_column(String(255), nullable=False)
    description: Mapped[str | None] = mapped_column(Text, nullable=True)
    category: Mapped[str] = mapped_column(String(50), nullable=False, default="other")
    interface_type: Mapped[str] = mapped_column(
        String(20), nullable=False, default="web"
    )
    requires_port: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
    default_port: Mapped[int] = mapped_column(nullable=False)
    definition_type: Mapped[str] = mapped_column(
        String(16), nullable=False, default="legacy"
    )  # "legacy" | "manifest"
    manifest_id: Mapped[uuid.UUID | None] = mapped_column(
        UUID(),
        ForeignKey("tool_definition_manifests.id"),
        nullable=True,
    )
    compose_template: Mapped[str | None] = mapped_column(Text, nullable=True)
    dockerfile_template: Mapped[str | None] = mapped_column(Text, nullable=True)
    build_context: Mapped[dict | None] = mapped_column(
        JSON, default=dict, nullable=True
    )
    readiness_probe: Mapped[dict | None] = mapped_column(JSON, nullable=True)
    startup_command: Mapped[str | None] = mapped_column(Text, nullable=True)
    home_directory: Mapped[str] = mapped_column(
        String(255), nullable=False, default="/home/user"
    )
    required_variables: Mapped[list[str]] = mapped_column(
        JSON, default=list, nullable=False
    )
    created_by_id: Mapped[uuid.UUID | None] = mapped_column(
        UUID(),
        ForeignKey("users.id"),
        nullable=True,
    )

    manifest: Mapped["ToolDefinitionManifest | None"] = relationship(
        foreign_keys=[manifest_id],
    )
    created_by: Mapped["User | None"] = relationship()
