from sqlalchemy import ForeignKey, Numeric, String, DateTime, Enum, Float
from sqlalchemy.orm import Mapped, mapped_column, relationship
from datetime import datetime
from decimal import Decimal
import enum
from app.database import Base


class SpreadBetStatus(enum.Enum):
    OPEN = "open"  # Created, waiting for taker
    MATCHED = "matched"  # Taker found, both funds locked
    COMPLETED = "completed"  # Game finished, winner paid
    CANCELLED = "cancelled"  # Creator cancelled before match
    DISPUTED = "disputed"  # Settlement disputed


class TeamSide(enum.Enum):
    HOME = "home"
    AWAY = "away"


class SpreadBet(Base):
    """Spread bets on sporting events"""
    __tablename__ = "spread_bets"

    id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)

    # Event this bet is for
    event_id: Mapped[int] = mapped_column(ForeignKey("sport_events.id"))

    # Spread value (e.g., -3, +3, 0)
    # Positive = team is underdog, negative = team is favorite
    spread: Mapped[float] = mapped_column(Float)

    # Which team (home or away)
    team: Mapped[TeamSide] = mapped_column(Enum(TeamSide))

    # Users
    creator_id: Mapped[int] = mapped_column(ForeignKey("users.id"))
    taker_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"), nullable=True)

    # Stake amount (both users stake this amount)
    stake_amount: Mapped[Decimal] = mapped_column(Numeric(12, 2))

    # House commission (default 10%, adjustable by admin)
    house_commission_percent: Mapped[Decimal] = mapped_column(Numeric(5, 2), default=Decimal("10.00"))

    # Status
    status: Mapped[SpreadBetStatus] = mapped_column(Enum(SpreadBetStatus), default=SpreadBetStatus.OPEN)

    # Result
    winner_id: Mapped[int | None] = mapped_column(ForeignKey("users.id"), nullable=True)
    settled_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)

    # Payout amounts (calculated after settlement)
    payout_to_winner: Mapped[Decimal | None] = mapped_column(Numeric(12, 2), nullable=True)
    house_fee_collected: Mapped[Decimal | None] = mapped_column(Numeric(12, 2), nullable=True)

    # Timestamps
    created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow)
    matched_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
    updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    # Relationships
    event: Mapped["SportEvent"] = relationship(back_populates="spread_bets")
    creator: Mapped["User"] = relationship(foreign_keys=[creator_id], back_populates="created_spread_bets")
    taker: Mapped["User | None"] = relationship(foreign_keys=[taker_id], back_populates="taken_spread_bets")
    winner: Mapped["User | None"] = relationship(foreign_keys=[winner_id])
