from datetime import datetime

from sqlalchemy import Boolean, DateTime, ForeignKey, SmallInteger, String, func, text
from sqlalchemy.orm import Mapped, mapped_column, relationship

from app.core.database import Base


class Encounter(Base):
    __tablename__ = "encounters"

    id: Mapped[int] = mapped_column(primary_key=True)
    run_id: Mapped[int] = mapped_column(ForeignKey("nuzlocke_runs.id"), index=True)
    route_id: Mapped[int] = mapped_column(ForeignKey("routes.id"), index=True)
    pokemon_id: Mapped[int] = mapped_column(ForeignKey("pokemon.id"), index=True)
    nickname: Mapped[str | None] = mapped_column(String(50))
    status: Mapped[str] = mapped_column(String(20))  # caught, fainted, missed
    catch_level: Mapped[int | None] = mapped_column(SmallInteger)
    faint_level: Mapped[int | None] = mapped_column(SmallInteger)
    death_cause: Mapped[str | None] = mapped_column(String(100))
    current_pokemon_id: Mapped[int | None] = mapped_column(
        ForeignKey("pokemon.id"), index=True
    )
    is_shiny: Mapped[bool] = mapped_column(Boolean, default=False, server_default=text("false"))
    caught_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), server_default=func.now()
    )

    run: Mapped["NuzlockeRun"] = relationship(back_populates="encounters")
    route: Mapped["Route"] = relationship(back_populates="encounters")
    pokemon: Mapped["Pokemon"] = relationship(
        foreign_keys=[pokemon_id], back_populates="encounters"
    )
    current_pokemon: Mapped["Pokemon | None"] = relationship(
        foreign_keys=[current_pokemon_id]
    )

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