from datetime import datetime, timedelta, timezone

from sqlalchemy import Boolean, DateTime, ForeignKey, Integer, Text
from sqlalchemy.orm import Mapped, mapped_column

from fabledassistant.models import Base


class Event(Base):
    __tablename__ = "events"

    id: Mapped[int] = mapped_column(primary_key=True)
    user_id: Mapped[int] = mapped_column(
        Integer, ForeignKey("users.id", ondelete="CASCADE")
    )
    project_id: Mapped[int | None] = mapped_column(
        Integer, ForeignKey("projects.id", ondelete="SET NULL"), nullable=True
    )
    # iCal UID for Radicale linkage (unique per user)
    uid: Mapped[str] = mapped_column(Text)
    title: Mapped[str] = mapped_column(Text, default="")
    start_dt: Mapped[datetime] = mapped_column(DateTime(timezone=True))
    # Duration in minutes; NULL = point event with no end specified.
    # Replaces the prior `end_dt` column (Fable #160 / migration 0043).
    # The DB has a CHECK constraint that this is NULL or >= 0, so an
    # event whose end is before its start is structurally inexpressible.
    duration_minutes: Mapped[int | None] = mapped_column(Integer, nullable=True)
    all_day: Mapped[bool] = mapped_column(Boolean, default=False)
    description: Mapped[str] = mapped_column(Text, default="")
    location: Mapped[str] = mapped_column(Text, default="")
    caldav_uid: Mapped[str] = mapped_column(Text, default="")
    color: Mapped[str] = mapped_column(Text, default="")
    recurrence: Mapped[str | None] = mapped_column(Text, nullable=True)
    reminder_minutes: Mapped[int | None] = mapped_column(Integer, nullable=True)
    reminder_sent_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
    created_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)
    )
    updated_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True),
        default=lambda: datetime.now(timezone.utc),
        onupdate=lambda: datetime.now(timezone.utc),
    )

    @property
    def end_dt(self) -> datetime | None:
        """Derived end datetime: ``start_dt + duration_minutes``.

        Returns ``None`` for point events (``duration_minutes is None``).
        Computed at access time rather than stored — a stored end was
        the source of the "end before start" corruption that motivated
        this redesign.
        """
        if self.duration_minutes is None:
            return None
        return self.start_dt + timedelta(minutes=self.duration_minutes)

    def to_dict(self) -> dict:
        end_dt = self.end_dt
        return {
            "id": self.id,
            "user_id": self.user_id,
            "uid": self.uid,
            "caldav_uid": self.caldav_uid,
            "project_id": self.project_id,
            "title": self.title,
            "start_dt": self.start_dt.isoformat() if self.start_dt else None,
            "end_dt": end_dt.isoformat() if end_dt else None,
            "duration_minutes": self.duration_minutes,
            "all_day": self.all_day,
            "description": self.description,
            "location": self.location,
            "color": self.color,
            "recurrence": self.recurrence,
            "reminder_minutes": self.reminder_minutes,
            "created_at": self.created_at.isoformat() if self.created_at else None,
            "updated_at": self.updated_at.isoformat() if self.updated_at else None,
        }
