"""
轻量日历后端选择器。

不引入完整 provider 抽象层，只集中管理：
- 当前模式判断
- 事件读取
- 事件创建
- 事件删除
- Google 同步触发
"""

from __future__ import annotations

from dataclasses import dataclass
from datetime import datetime

from config.settings import (
    GCAL_CALENDAR_ID,
    GCAL_MAX_RETRIES,
    GCAL_SSL_VERIFY,
    GCAL_TIMEOUT,
    GCAL_TOKEN_PATH,
    PROXIES,
    TIMEZONE,
)
from gcal.client import CalendarClient
from gcal.models import CalendarEvent
from services import local_event_store
from services.google_integration import get_active_mode, sync_local_events_to_google


@dataclass
class EventView:
    event: CalendarEvent
    provider: str
    sync_state: str = ""


@dataclass
class EventCreateResult:
    provider: str
    event_id: str
    sync_state: str = ""


def _new_google_client() -> CalendarClient:
    return CalendarClient(
        token_path=GCAL_TOKEN_PATH,
        proxies=PROXIES,
        calendar_id=GCAL_CALENDAR_ID,
        timeout=GCAL_TIMEOUT,
        max_retries=GCAL_MAX_RETRIES,
        verify=GCAL_SSL_VERIFY,
    )


def active_provider() -> str:
    return get_active_mode()


def list_event_views(time_min: datetime, time_max: datetime) -> list[EventView]:
    provider = active_provider()
    if provider == "google":
        client = _new_google_client()
        return [
            EventView(event=event, provider="google", sync_state="")
            for event in client.list_events(time_min, time_max)
        ]

    records = local_event_store.list_records(time_min=time_min, time_max=time_max)
    return [
        EventView(
            event=local_event_store.record_to_event(record),
            provider="local",
            sync_state=record.get("sync_state", "local_only"),
        )
        for record in records
    ]


def list_events(time_min: datetime, time_max: datetime) -> list[CalendarEvent]:
    return [item.event for item in list_event_views(time_min, time_max)]


def create_event(
    summary: str,
    start: datetime,
    end: datetime,
    location: str = "",
    description: str = "",
    remind_minutes: int = 0,
) -> EventCreateResult:
    provider = active_provider()
    if provider == "google":
        client = _new_google_client()
        event_id = client.create_event(
            summary=summary,
            start=start,
            end=end,
            location=location,
            description=description,
            tz=TIMEZONE,
        )
        return EventCreateResult(provider="google", event_id=event_id, sync_state="")

    record = local_event_store.create_event(
        summary=summary,
        start=start,
        end=end,
        location=location,
        description=description,
        remind_minutes=remind_minutes,
    )
    return EventCreateResult(
        provider="local",
        event_id=record["id"],
        sync_state=record.get("sync_state", "local_only"),
    )


def delete_event(event_id: str) -> bool:
    provider = active_provider()
    if event_id.startswith("local_") or provider == "local":
        return local_event_store.delete_event(event_id)
    client = _new_google_client()
    client.delete_event(event_id)
    return True


def get_event_status(event_id: str) -> str | None:
    provider = active_provider()
    if event_id.startswith("local_") or provider == "local":
        return local_event_store.get_event_status(event_id)
    client = _new_google_client()
    return client.get_event_status(event_id)


def sync_local_events() -> dict:
    return sync_local_events_to_google()
