import uuid
from datetime import date, datetime

from sqlalchemy import String, Float, Integer, Date, DateTime, ForeignKey, Text, func
from sqlalchemy.dialects.postgresql import UUID, JSONB
from sqlalchemy.orm import Mapped, mapped_column

from backend.app.core.database import Base


class FitnessHistory(Base):
    __tablename__ = "fitness_history"

    id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
    rider_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("riders.id"))
    date: Mapped[date] = mapped_column(Date, index=True)
    ctl: Mapped[float] = mapped_column(Float, default=0)
    atl: Mapped[float] = mapped_column(Float, default=0)
    tsb: Mapped[float] = mapped_column(Float, default=0)
    ramp_rate: Mapped[float | None] = mapped_column(Float, nullable=True)


class PowerCurve(Base):
    __tablename__ = "power_curves"

    id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    activity_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("activities.id"))
    curve_data: Mapped[dict] = mapped_column(JSONB)  # {duration_seconds: max_power}


class DiaryEntry(Base):
    __tablename__ = "diary_entries"

    id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    activity_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("activities.id"), unique=True)
    ai_summary: Mapped[str | None] = mapped_column(Text, nullable=True)
    rider_notes: Mapped[str | None] = mapped_column(Text, nullable=True)
    mood: Mapped[str | None] = mapped_column(String(50), nullable=True)
    rpe: Mapped[int | None] = mapped_column(Integer, nullable=True)
    sleep_hours: Mapped[float | None] = mapped_column(Float, nullable=True)

    created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
