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

from app.core.database import Base


class ParticipantRole(str, Enum):
    PARTICIPANT = "participant"
    ORGANIZER = "organizer"


class Participant(Base):
    __tablename__ = "participants"
    __table_args__ = (
        UniqueConstraint("user_id", "marathon_id", name="unique_user_marathon"),
    )

    id: Mapped[int] = mapped_column(primary_key=True)
    user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), index=True)
    marathon_id: Mapped[int] = mapped_column(ForeignKey("marathons.id", ondelete="CASCADE"), index=True)
    role: Mapped[str] = mapped_column(String(20), default=ParticipantRole.PARTICIPANT.value)
    total_points: Mapped[int] = mapped_column(Integer, default=0)
    current_streak: Mapped[int] = mapped_column(Integer, default=0)
    drop_count: Mapped[int] = mapped_column(Integer, default=0)  # For progressive penalty
    joined_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow)

    # Relationships
    user: Mapped["User"] = relationship("User", back_populates="participations")
    marathon: Mapped["Marathon"] = relationship("Marathon", back_populates="participants")
    assignments: Mapped[list["Assignment"]] = relationship(
        "Assignment",
        back_populates="participant",
        cascade="all, delete-orphan"
    )

    @property
    def is_organizer(self) -> bool:
        return self.role == ParticipantRole.ORGANIZER.value
