from datetime import datetime

from sqlalchemy import DateTime, ForeignKey, String, func
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import Mapped, mapped_column, relationship

from app.core.database import Base


class NuzlockeRun(Base):
    __tablename__ = "nuzlocke_runs"

    id: Mapped[int] = mapped_column(primary_key=True)
    game_id: Mapped[int] = mapped_column(ForeignKey("games.id"), index=True)
    name: Mapped[str] = mapped_column(String(100))
    status: Mapped[str] = mapped_column(String(20), index=True)  # active, completed, failed
    rules: Mapped[dict] = mapped_column(JSONB, default=dict)
    started_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), server_default=func.now()
    )
    completed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
    hof_encounter_ids: Mapped[list[int] | None] = mapped_column(JSONB, default=None)

    game: Mapped["Game"] = relationship(back_populates="runs")
    encounters: Mapped[list["Encounter"]] = relationship(back_populates="run")
    boss_results: Mapped[list["BossResult"]] = relationship(back_populates="run")

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