from datetime import datetime
from enum import Enum
from sqlalchemy import String, Text, DateTime, ForeignKey, Integer, Boolean
from sqlalchemy.orm import Mapped, mapped_column, relationship

from app.core.database import Base


class ChallengeType(str, Enum):
    COMPLETION = "completion"
    NO_DEATH = "no_death"
    SPEEDRUN = "speedrun"
    COLLECTION = "collection"
    ACHIEVEMENT = "achievement"
    CHALLENGE_RUN = "challenge_run"
    SCORE_ATTACK = "score_attack"
    TIME_TRIAL = "time_trial"


class Difficulty(str, Enum):
    EASY = "easy"
    MEDIUM = "medium"
    HARD = "hard"


class ProofType(str, Enum):
    SCREENSHOT = "screenshot"
    VIDEO = "video"
    STEAM = "steam"


class ChallengeStatus(str, Enum):
    PENDING = "pending"
    APPROVED = "approved"
    REJECTED = "rejected"


class Challenge(Base):
    __tablename__ = "challenges"

    id: Mapped[int] = mapped_column(primary_key=True)
    game_id: Mapped[int] = mapped_column(ForeignKey("games.id", ondelete="CASCADE"), index=True)
    title: Mapped[str] = mapped_column(String(100), nullable=False)
    description: Mapped[str] = mapped_column(Text, nullable=False)
    type: Mapped[str] = mapped_column(String(30), nullable=False)
    difficulty: Mapped[str] = mapped_column(String(10), nullable=False)
    points: Mapped[int] = mapped_column(Integer, nullable=False)
    estimated_time: Mapped[int | None] = mapped_column(Integer, nullable=True)  # in minutes
    proof_type: Mapped[str] = mapped_column(String(20), nullable=False)
    proof_hint: Mapped[str | None] = mapped_column(Text, nullable=True)
    is_generated: Mapped[bool] = mapped_column(Boolean, default=True)
    created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow)

    # Proposed challenges support
    proposed_by_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"), nullable=True)
    status: Mapped[str] = mapped_column(String(20), default="approved")  # pending, approved, rejected

    # Relationships
    game: Mapped["Game"] = relationship("Game", back_populates="challenges")
    proposed_by: Mapped["User"] = relationship("User", foreign_keys=[proposed_by_id])
    assignments: Mapped[list["Assignment"]] = relationship(
        "Assignment",
        back_populates="challenge"
    )
