"""Google Calendar API service wrapper."""

from __future__ import annotations

from typing import Any, Optional

from googleapiclient.discovery import build

from ..auth.oauth import get_credentials, resolve_profile


def _get_service(profile: Optional[str] = None):
    return build("calendar", "v3", credentials=get_credentials(resolve_profile(profile)))


# ---------------------------------------------------------------------------
# Public API
# ---------------------------------------------------------------------------

def list_events(
    profile: Optional[str] = None,
    calendar_id: str = "primary",
    time_min: Optional[str] = None,
    time_max: Optional[str] = None,
    query: Optional[str] = None,
    max_results: int = 25,
    page_token: Optional[str] = None,
) -> dict[str, Any]:
    svc = _get_service(profile)
    kwargs: dict[str, Any] = {
        "calendarId": calendar_id,
        "maxResults": max_results,
        "singleEvents": True,
        "orderBy": "startTime",
    }
    if time_min:
        kwargs["timeMin"] = time_min
    if time_max:
        kwargs["timeMax"] = time_max
    if query:
        kwargs["q"] = query
    if page_token:
        kwargs["pageToken"] = page_token

    res = svc.events().list(**kwargs).execute()
    events = [
        {
            "id": e["id"],
            "summary": e.get("summary"),
            "description": (e.get("description") or "")[:500],
            "location": e.get("location"),
            "start": e.get("start", {}).get("dateTime") or e.get("start", {}).get("date"),
            "end": e.get("end", {}).get("dateTime") or e.get("end", {}).get("date"),
            "attendees": [
                {"email": a["email"], "responseStatus": a.get("responseStatus")}
                for a in e.get("attendees", [])
            ],
            "hangoutLink": e.get("hangoutLink"),
            "htmlLink": e.get("htmlLink"),
            "status": e.get("status"),
        }
        for e in res.get("items", [])
    ]
    return {"nextPageToken": res.get("nextPageToken"), "events": events}


def create_event(
    summary: str,
    start: str,
    end: str,
    profile: Optional[str] = None,
    calendar_id: str = "primary",
    description: Optional[str] = None,
    location: Optional[str] = None,
    attendees: Optional[list[str]] = None,
    send_updates: str = "none",
) -> dict[str, Any]:
    svc = _get_service(profile)
    body: dict[str, Any] = {
        "summary": summary,
        "start": {"dateTime": start},
        "end": {"dateTime": end},
    }
    if description:
        body["description"] = description
    if location:
        body["location"] = location
    if attendees:
        body["attendees"] = [{"email": e} for e in attendees]

    res = svc.events().insert(
        calendarId=calendar_id, body=body, sendUpdates=send_updates,
    ).execute()
    return {
        "id": res["id"],
        "summary": res.get("summary"),
        "start": res.get("start", {}).get("dateTime"),
        "end": res.get("end", {}).get("dateTime"),
        "htmlLink": res.get("htmlLink"),
        "status": "created",
    }


def update_event(
    event_id: str,
    profile: Optional[str] = None,
    calendar_id: str = "primary",
    summary: Optional[str] = None,
    description: Optional[str] = None,
    location: Optional[str] = None,
    start: Optional[str] = None,
    end: Optional[str] = None,
) -> dict[str, Any]:
    svc = _get_service(profile)
    body: dict[str, Any] = {}
    if summary:
        body["summary"] = summary
    if description:
        body["description"] = description
    if location:
        body["location"] = location
    if start:
        body["start"] = {"dateTime": start}
    if end:
        body["end"] = {"dateTime": end}

    res = svc.events().patch(
        calendarId=calendar_id, eventId=event_id, body=body,
    ).execute()
    return {
        "id": res["id"],
        "summary": res.get("summary"),
        "start": res.get("start", {}).get("dateTime"),
        "end": res.get("end", {}).get("dateTime"),
        "status": "updated",
    }


def delete_event(
    event_id: str,
    profile: Optional[str] = None,
    calendar_id: str = "primary",
) -> dict[str, Any]:
    svc = _get_service(profile)
    svc.events().delete(calendarId=calendar_id, eventId=event_id).execute()
    return {"eventId": event_id, "status": "deleted"}


def free_busy(
    time_min: str,
    time_max: str,
    profile: Optional[str] = None,
    emails: Optional[list[str]] = None,
) -> dict[str, Any]:
    svc = _get_service(profile)
    items = [{"id": e} for e in (emails or ["primary"])]
    res = svc.freebusy().query(body={
        "timeMin": time_min,
        "timeMax": time_max,
        "items": items,
    }).execute()
    busy: dict[str, list] = {}
    for cal_id, data in (res.get("calendars") or {}).items():
        busy[cal_id] = data.get("busy", [])
    return {"timeMin": time_min, "timeMax": time_max, "busy": busy}


def list_calendars(profile: Optional[str] = None) -> list[dict[str, Any]]:
    svc = _get_service(profile)
    res = svc.calendarList().list().execute()
    return [
        {
            "id": c["id"],
            "summary": c.get("summary"),
            "description": c.get("description"),
            "primary": c.get("primary", False),
            "accessRole": c.get("accessRole"),
            "timeZone": c.get("timeZone"),
        }
        for c in res.get("items", [])
    ]
