"""Google Calendar 事件数据模型。"""

from __future__ import annotations

from dataclasses import dataclass
from datetime import datetime, timezone


@dataclass
class CalendarEvent:
    """
    结构化的 Google Calendar 事件。
    start / end 始终是 timezone-aware datetime。
    """

    id: str
    summary: str
    start: datetime
    end: datetime
    status: str      = "confirmed"   # "confirmed" | "cancelled" | "tentative"
    is_all_day: bool = False
    location: str    = ""
    description: str = ""

    # ── 业务判断 ──────────────────────────────────────────────────

    def is_past(self, now: datetime | None = None) -> bool:
        """事件是否已经结束。"""
        if now is None:
            now = datetime.now(timezone.utc)
        return _aware(self.end) < _aware(now)

    def duration_minutes(self) -> int:
        return int((self.end - self.start).total_seconds() / 60)

    # ── 快照序列化 ─────────────────────────────────────────────────

    def to_dict(self) -> dict:
        return {
            "id":          self.id,
            "summary":     self.summary,
            "start":       self.start.isoformat(),
            "end":         self.end.isoformat(),
            "status":      self.status,
            "is_all_day":  self.is_all_day,
            "location":    self.location,
            "description": self.description,
        }

    @classmethod
    def from_dict(cls, d: dict) -> CalendarEvent:
        return cls(
            id          = d["id"],
            summary     = d.get("summary", "无标题"),
            start       = _parse_iso(d["start"]),
            end         = _parse_iso(d["end"]),
            status      = d.get("status", "confirmed"),
            is_all_day  = d.get("is_all_day", False),
            location    = d.get("location", ""),
            description = d.get("description", ""),
        )

    # ── 标准协议 ───────────────────────────────────────────────────

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, CalendarEvent):
            return False
        return self.id == other.id

    def __hash__(self) -> int:
        return hash(self.id)

    def __repr__(self) -> str:
        t = self.start.strftime("%m-%d %H:%M") if not self.is_all_day else self.start.strftime("%m-%d 全天")
        return f"<CalendarEvent {t} {self.summary!r}>"


# ─────────────────────────── 内部工具 ────────────────────────────


def _aware(dt: datetime) -> datetime:
    if dt.tzinfo is None:
        return dt.replace(tzinfo=timezone.utc)
    return dt


def _parse_iso(s: str) -> datetime:
    dt = datetime.fromisoformat(s)
    if dt.tzinfo is None:
        return dt.replace(tzinfo=timezone.utc)
    return dt
