from sqlalchemy import ForeignKey, SmallInteger, String, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column, relationship

from app.core.database import Base


class Route(Base):
    __tablename__ = "routes"
    __table_args__ = (
        UniqueConstraint("version_group_id", "name", name="uq_routes_version_group_name"),
    )

    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str] = mapped_column(String(100))
    version_group_id: Mapped[int] = mapped_column(
        ForeignKey("version_groups.id"), index=True
    )
    order: Mapped[int] = mapped_column(SmallInteger)
    parent_route_id: Mapped[int | None] = mapped_column(
        ForeignKey("routes.id", ondelete="CASCADE"), index=True, default=None
    )
    pinwheel_zone: Mapped[int | None] = mapped_column(SmallInteger, default=None)

    version_group: Mapped["VersionGroup"] = relationship(back_populates="routes")
    route_encounters: Mapped[list["RouteEncounter"]] = relationship(
        back_populates="route"
    )
    encounters: Mapped[list["Encounter"]] = relationship(back_populates="route")

    # Self-referential relationships for route grouping
    parent: Mapped["Route | None"] = relationship(
        back_populates="children", remote_side=[id]
    )
    children: Mapped[list["Route"]] = relationship(
        back_populates="parent", cascade="all, delete-orphan"
    )

    def __repr__(self) -> str:
        return f"<Route(id={self.id}, name='{self.name}')>"
