"""Google Calendar: sign-in (OAuth), calendar list, event cache, create/delete.

Talks to Google's REST API with `requests` directly (no heavy client library),
which keeps installs simple on shared hosting.

Events are copied into the local `events` table for the next SYNC_DAYS_AHEAD
days. Pages and the widget read that copy, so they stay fast; it's refreshed
when it's older than SYNC_MAX_AGE_MINUTES (or by cron running sync.py).
"""
import json
import secrets
import time
from datetime import date, datetime, timedelta
from urllib.parse import quote, urlencode
from zoneinfo import ZoneInfo

import requests

import config
import db

AUTH_URL = "https://accounts.google.com/o/oauth2/v2/auth"
TOKEN_URL = "https://oauth2.googleapis.com/token"
REVOKE_URL = "https://oauth2.googleapis.com/revoke"
API = "https://www.googleapis.com/calendar/v3"
SCOPES = [
    "https://www.googleapis.com/auth/calendar.calendarlist.readonly",  # list your calendars
    "https://www.googleapis.com/auth/calendar.events",                 # read/add/delete events
]
TIMEOUT = 20

_http = requests.Session()   # reuses connections to Google between calls


class GoogleError(Exception):
    pass


def configured() -> bool:
    return bool(config.GOOGLE_CLIENT_ID and config.GOOGLE_CLIENT_SECRET)


def connected(conn) -> bool:
    return bool(db.get_setting(conn, "google_refresh_token"))


# --------------------------------------------------------------------------
# Sign-in
# --------------------------------------------------------------------------

def new_state() -> str:
    return secrets.token_urlsafe(24)


def auth_url(state: str) -> str:
    return AUTH_URL + "?" + urlencode({
        "client_id": config.GOOGLE_CLIENT_ID,
        "redirect_uri": config.GOOGLE_REDIRECT_URI,
        "response_type": "code",
        "scope": " ".join(SCOPES),
        "access_type": "offline",      # we need a refresh token...
        "prompt": "consent",           # ...and Google only re-issues it with consent
        "include_granted_scopes": "true",
        "state": state,
    })


def _save_token(conn, tok: dict) -> None:
    if tok.get("refresh_token"):
        db.set_setting(conn, "google_refresh_token", tok["refresh_token"])
    db.set_setting(conn, "google_access_token", tok["access_token"])
    db.set_setting(conn, "google_token_expiry", str(int(time.time()) + int(tok.get("expires_in", 3600)) - 60))


def exchange_code(conn, code: str) -> None:
    r = _http.post(TOKEN_URL, data={
        "code": code,
        "client_id": config.GOOGLE_CLIENT_ID,
        "client_secret": config.GOOGLE_CLIENT_SECRET,
        "redirect_uri": config.GOOGLE_REDIRECT_URI,
        "grant_type": "authorization_code",
    }, timeout=TIMEOUT)
    if r.status_code != 200:
        raise GoogleError(f"Google sign-in failed: {_error_text(r)}")
    _save_token(conn, r.json())
    conn.commit()


def _access_token(conn) -> str:
    token = db.get_setting(conn, "google_access_token")
    if token and time.time() < int(db.get_setting(conn, "google_token_expiry", "0") or 0):
        return token
    refresh = db.get_setting(conn, "google_refresh_token")
    if not refresh:
        raise GoogleError("Google Calendar isn't connected.")
    r = _http.post(TOKEN_URL, data={
        "client_id": config.GOOGLE_CLIENT_ID,
        "client_secret": config.GOOGLE_CLIENT_SECRET,
        "refresh_token": refresh,
        "grant_type": "refresh_token",
    }, timeout=TIMEOUT)
    if r.status_code != 200:
        if "invalid_grant" in r.text:
            # Revoked, password changed, or the Google project is still in "Testing"
            # mode (Google expires those after 7 days). Only a reconnect fixes it.
            db.delete_setting(conn, "google_refresh_token")
            conn.commit()
            raise GoogleError("Google access expired or was revoked. Reconnect in Settings.")
        raise GoogleError(f"Couldn't refresh Google access: {_error_text(r)}")
    _save_token(conn, r.json())
    conn.commit()
    return db.get_setting(conn, "google_access_token")


def _error_text(r) -> str:
    try:
        body = r.json()
        err = body.get("error")
        if isinstance(err, dict):
            return err.get("message", str(err))[:300]
        return (body.get("error_description") or err or r.text)[:300]
    except ValueError:
        return r.text[:300]


def _api(conn, method: str, path: str, params=None, body=None):
    headers = {"Authorization": f"Bearer {_access_token(conn)}"}
    if body is not None:
        headers["Content-Type"] = "application/json"
    r = _http.request(method, API + path, headers=headers, params=params,
                      data=json.dumps(body) if body is not None else None, timeout=TIMEOUT)
    if r.status_code >= 400:
        raise GoogleError(f"Google Calendar error ({r.status_code}): {_error_text(r)}")
    return r.json() if r.content else {}


def _cal_path(calendar_id: str) -> str:
    return "/calendars/" + quote(calendar_id, safe="")


def disconnect(conn) -> None:
    token = db.get_setting(conn, "google_refresh_token")
    if token:
        try:
            _http.post(REVOKE_URL, params={"token": token}, timeout=10)
        except requests.RequestException:
            pass   # still forget it locally
    for key in ("google_refresh_token", "google_access_token", "google_token_expiry",
                "last_sync", "last_sync_error"):
        db.delete_setting(conn, key)
    conn.execute("DELETE FROM events")
    conn.execute("DELETE FROM calendars")
    conn.commit()


# --------------------------------------------------------------------------
# Calendars + events
# --------------------------------------------------------------------------

def refresh_calendars(conn) -> None:
    items, page = [], None
    while True:
        params = {"minAccessRole": "reader"}
        if page:
            params["pageToken"] = page
        data = _api(conn, "GET", "/users/me/calendarList", params=params)
        items += data.get("items", [])
        page = data.get("nextPageToken")
        if not page:
            break

    known = {r["id"] for r in conn.execute("SELECT id FROM calendars")}
    seen = set()
    for c in items:
        cid = c["id"]
        seen.add(cid)
        name = c.get("summaryOverride") or c.get("summary") or cid
        color = c.get("backgroundColor", "#4285f4")
        role = c.get("accessRole", "reader")
        if cid in known:   # keep your show/hide and default choices
            conn.execute("UPDATE calendars SET summary=?, color=?, access_role=? WHERE id=?",
                         (name, color, role, cid))
        else:              # new: shown if it's checked in Google Calendar
            conn.execute("INSERT INTO calendars(id, summary, color, access_role, visible, is_default) "
                         "VALUES(?,?,?,?,?,?)",
                         (cid, name, color, role, 1 if c.get("selected") else 0, 1 if c.get("primary") else 0))
    for cid in known - seen:
        conn.execute("DELETE FROM calendars WHERE id=?", (cid,))
        conn.execute("DELETE FROM events WHERE calendar_id=?", (cid,))


def _bounds(event: dict, tz: ZoneInfo):
    """(start, end, start_ts, end_ts, all_day) for a Google event."""
    s, e = event.get("start", {}), event.get("end", {})
    if "date" in s:   # all-day; Google's end date is exclusive
        sd, ed = date.fromisoformat(s["date"]), date.fromisoformat(e.get("date", s["date"]))
        if ed <= sd:
            ed = sd + timedelta(days=1)
        midnight = lambda d: int(datetime.combine(d, datetime.min.time(), tz).timestamp())  # noqa: E731
        return s["date"], ed.isoformat(), midnight(sd), midnight(ed), 1
    sdt = datetime.fromisoformat(s["dateTime"].replace("Z", "+00:00"))
    edt = datetime.fromisoformat(e.get("dateTime", s["dateTime"]).replace("Z", "+00:00"))
    return s["dateTime"], e.get("dateTime", s["dateTime"]), int(sdt.timestamp()), int(edt.timestamp()), 0


def sync_events(conn, today: date) -> None:
    tz = ZoneInfo(config.TIMEZONE)
    start = datetime.combine(today - timedelta(days=1), datetime.min.time(), tz)
    end = datetime.combine(today + timedelta(days=config.SYNC_DAYS_AHEAD), datetime.min.time(), tz)

    for cal in conn.execute("SELECT id FROM calendars WHERE visible=1").fetchall():
        cid = cal["id"]
        events, page = [], None
        while True:
            params = {"timeMin": start.isoformat(), "timeMax": end.isoformat(),
                      "singleEvents": "true",          # expand repeating events into dates
                      "orderBy": "startTime", "maxResults": "250", "timeZone": config.TIMEZONE}
            if page:
                params["pageToken"] = page
            data = _api(conn, "GET", _cal_path(cid) + "/events", params=params)
            events += data.get("items", [])
            page = data.get("nextPageToken")
            if not page:
                break

        rows = []
        for ev in events:
            if ev.get("status") == "cancelled" or "start" not in ev:
                continue
            if any(a.get("self") and a.get("responseStatus") == "declined" for a in ev.get("attendees", [])):
                continue   # you said no
            s, e, s_ts, e_ts, all_day = _bounds(ev, tz)
            rows.append((cid, ev["id"], ev.get("summary") or "(no title)", s, e, s_ts, e_ts, all_day,
                         ev.get("location", ""), ev.get("htmlLink", ""), 1 if ev.get("recurringEventId") else 0))
        conn.execute("DELETE FROM events WHERE calendar_id=?", (cid,))
        conn.executemany(
            "INSERT OR REPLACE INTO events(calendar_id, id, summary, start, end, start_ts, end_ts, all_day, "
            "location, html_link, recurring) VALUES(?,?,?,?,?,?,?,?,?,?,?)", rows)

    conn.execute("DELETE FROM events WHERE calendar_id NOT IN (SELECT id FROM calendars WHERE visible=1)")
    db.set_setting(conn, "last_sync", str(int(time.time())))
    db.delete_setting(conn, "last_sync_error")


def full_sync(conn, today: date) -> None:
    refresh_calendars(conn)
    sync_events(conn, today)
    conn.commit()


def sync_if_stale(conn, today: date, force: bool = False):
    """Refresh the local copy if it's old. Never raises; returns an error message or None."""
    if not (configured() and connected(conn)):
        return None
    last = int(db.get_setting(conn, "last_sync", "0") or 0)
    if not force and time.time() - last < config.SYNC_MAX_AGE_MINUTES * 60:
        return None
    try:
        full_sync(conn, today)
        return None
    except (GoogleError, requests.RequestException, KeyError, ValueError) as exc:
        conn.rollback()
        msg = str(exc)[:300] if isinstance(exc, GoogleError) else f"Couldn't reach Google ({type(exc).__name__})."
        db.set_setting(conn, "last_sync_error", msg)
        # Count the failed try as a sync so a broken connection doesn't slow every page.
        db.set_setting(conn, "last_sync", str(int(time.time())))
        conn.commit()
        return msg


def create_event(conn, calendar_id: str, title: str, day: date, start_time=None, end_time=None,
                 rrule=None, notes: str = "") -> dict:
    body = {"summary": title}
    if notes:
        body["description"] = notes
    if start_time:
        sh, sm = map(int, start_time.split(":"))
        start_dt = datetime(day.year, day.month, day.day, sh, sm)
        if end_time:
            eh, em = map(int, end_time.split(":"))
            end_dt = datetime(day.year, day.month, day.day, eh, em)
            if end_dt <= start_dt:
                end_dt += timedelta(days=1)    # e.g. 10pm-1am
        else:
            end_dt = start_dt + timedelta(hours=1)
        body["start"] = {"dateTime": start_dt.isoformat(), "timeZone": config.TIMEZONE}
        body["end"] = {"dateTime": end_dt.isoformat(), "timeZone": config.TIMEZONE}
    else:
        body["start"] = {"date": day.isoformat()}
        body["end"] = {"date": (day + timedelta(days=1)).isoformat()}
    if rrule:
        body["recurrence"] = [f"RRULE:{rrule}"]
    return _api(conn, "POST", _cal_path(calendar_id) + "/events", body=body)


def delete_event(conn, calendar_id: str, event_id: str) -> None:
    """Deletes one event; for a repeating event this removes just that occurrence."""
    try:
        _api(conn, "DELETE", _cal_path(calendar_id) + "/events/" + quote(event_id, safe=""))
    except GoogleError as exc:
        if "(410)" not in str(exc) and "(404)" not in str(exc):   # already gone is fine
            raise
    conn.execute("DELETE FROM events WHERE calendar_id=? AND id=?", (calendar_id, event_id))
    conn.commit()
