#!/usr/bin/env python3
"""Check Google Calendar events. Uses service account. Zero external dependencies."""
import json
import os
import sys
import urllib.request
import urllib.error
import urllib.parse
import time
import base64
import subprocess
import tempfile
from datetime import datetime, timedelta, timezone

SA_FILE = os.path.expanduser("~/.openclaw/secrets/google-calendar-sa.json")
CALENDARS = ["mike@nomorechores.com", "mikeziarko@gmail.com"]

def get_access_token():
    sa = json.load(open(SA_FILE))
    header = base64.urlsafe_b64encode(json.dumps({"alg": "RS256", "typ": "JWT"}).encode()).rstrip(b"=").decode()
    now = int(time.time())
    claims = {
        "iss": sa["client_email"],
        "scope": "https://www.googleapis.com/auth/calendar.readonly",
        "aud": "https://oauth2.googleapis.com/token",
        "iat": now,
        "exp": now + 3600,
    }
    payload = base64.urlsafe_b64encode(json.dumps(claims).encode()).rstrip(b"=").decode()
    msg = f"{header}.{payload}".encode()

    with tempfile.NamedTemporaryFile(mode="w", suffix=".pem", delete=False) as f:
        f.write(sa["private_key"])
        kf = f.name
    try:
        sig = base64.urlsafe_b64encode(
            subprocess.run(["openssl", "dgst", "-sha256", "-sign", kf], input=msg, capture_output=True).stdout
        ).rstrip(b"=").decode()
    finally:
        os.unlink(kf)

    data = urllib.parse.urlencode({
        "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
        "assertion": f"{header}.{payload}.{sig}",
    }).encode()
    resp = json.loads(urllib.request.urlopen(urllib.request.Request("https://oauth2.googleapis.com/token", data=data)).read())
    return resp["access_token"]

def check_calendar(hours=48):
    token = get_access_token()
    now = datetime.now(timezone.utc)
    time_min = now.strftime("%Y-%m-%dT%H:%M:%SZ")
    time_max = (now + timedelta(hours=hours)).strftime("%Y-%m-%dT%H:%M:%SZ")

    for cal_id in CALENDARS:
        label = "Work" if "nomorechores" in cal_id else "Personal"
        try:
            params = urllib.parse.urlencode({
                "timeMin": time_min,
                "timeMax": time_max,
                "singleEvents": "true",
                "orderBy": "startTime",
                "maxResults": 15,
            })
            url = f"https://www.googleapis.com/calendar/v3/calendars/{urllib.parse.quote(cal_id)}/events?{params}"
            req = urllib.request.Request(url, headers={"Authorization": f"Bearer {token}"})
            data = json.loads(urllib.request.urlopen(req).read())
            events = data.get("items", [])

            print(f"[{label}] {cal_id} - {len(events)} events in next {hours}h")
            for e in events:
                start = e.get("start", {}).get("dateTime", e.get("start", {}).get("date", "?"))
                summary = e.get("summary", "(no title)")
                location = e.get("location", "")
                line = f"  {start} | {summary}"
                if location:
                    line += f" @ {location}"
                print(line)
            if not events:
                print("  No upcoming events")
            print()

        except urllib.error.HTTPError as err:
            print(f"[{label}] {cal_id} - ERROR {err.code}")
            print()

if __name__ == "__main__":
    hours = int(sys.argv[1]) if len(sys.argv) > 1 else 48
    check_calendar(hours)
