import uuid

from sqlalchemy import Boolean, ForeignKey, String, Text
from sqlalchemy.dialects.postgresql import JSONB, UUID
from sqlalchemy.orm import Mapped, mapped_column, relationship

from api.models.base import Base, TimestampMixin, new_uuid


class WorkplanLaunchRequest(Base, TimestampMixin):
    __tablename__ = "workplan_launch_requests"

    id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True), primary_key=True, default=new_uuid
    )
    workplan_id: Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True),
        ForeignKey("workplans.id", ondelete="CASCADE"),
        nullable=False,
        index=True,
    )
    requested_by: Mapped[str] = mapped_column(String(100), nullable=False, default="dashboard")
    requested_actor: Mapped[str | None] = mapped_column(String(100), nullable=True)
    launch_mode: Mapped[str] = mapped_column(String(20), nullable=False, default="queued", index=True)
    concurrency_mode: Mapped[str] = mapped_column(String(20), nullable=False, default="sequential", index=True)
    priority: Mapped[str | None] = mapped_column(String(20), nullable=True, index=True)
    repo_id: Mapped[uuid.UUID | None] = mapped_column(
        UUID(as_uuid=True),
        ForeignKey("managed_repos.id", ondelete="SET NULL"),
        nullable=True,
        index=True,
    )
    branch_preference: Mapped[str | None] = mapped_column(Text, nullable=True)
    immediate_pickup: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default="false")
    status: Mapped[str] = mapped_column(String(20), nullable=False, default="requested", server_default="requested", index=True)
    notes: Mapped[str | None] = mapped_column(Text, nullable=True)
    request_metadata: Mapped[dict] = mapped_column(JSONB, nullable=False, default=dict, server_default="{}")

    workplan: Mapped["Workplan"] = relationship("Workplan", back_populates="launch_requests")  # noqa: F821
