#!/usr/bin/env python3
"""
kiwitime - Google Calendar CLI via Python stdlib only

Usage:
    kiwitime list "Arbeit" 14
    kiwitime create "Ahmed und Talla" "Date" "2026-05-10T19:00:00+02:00" "2026-05-10T21:00:00+02:00" "Dinner"
    kiwitime delete "Arbeit" EVENT_ID

Pitfall: Pass friendly names (Arbeit, Uni, etc.), NOT the raw Google Calendar hash IDs.
"""

import sys
import os
import urllib.request
import urllib.parse
import json
import datetime

# === Configuration (edit these for your environment) ===
CALENDAR_MAP = {
    "Persönlich": "ahmed.aytac@gmail.com",
    "Ahmed und Talla": "872722c5e5aca6a340b4ef3e0481f4b433fc00d11efd040ae33acba93d1a7457@group.calendar.google.com",
    "Arbeit": "a2ac7dd225f2f31b217f7286a49e5827bf9b7b92b94f6903316376f4f587bab7@group.calendar.google.com",
    "Uni": "4a0a44b2d32f8c9b7190d8ae2dac38549702ebd022b7ecc8058a18856a53c3e1@group.calendar.google.com",
}
PRIMARY_CALENDAR = "ahmed.aytac@gmail.com"
TOKEN_URL = "https://oauth2.googleapis.com/token"
API_BASE = "https://www.googleapis.com/calendar/v3"

# Credentials: prefer env vars, fallback to hardcoded secrets
CLIENT_ID = os.environ.get("GOOGLE_CLIENT_ID") or "YOUR_CLIENT_ID_HERE"
CLIENT_SECRET = os.environ.get("GOOGLE_CLIENT_SECRET") or "YOUR_CLIENT_SECRET_HERE"
REFRESH_TOKEN = os.environ.get("GOOGLE_REFRESH_TOKEN") or "YOUR_REFRESH_TOKEN_HERE"


def get_access_token():
    data = urllib.parse.urlencode({
        "client_id": CLIENT_ID,
        "client_secret": CLIENT_SECRET,
        "refresh_token": REFRESH_TOKEN,
        "grant_type": "refresh_token",
    }).encode("utf-8")
    req = urllib.request.Request(TOKEN_URL, data=data, method="POST",
                                 headers={"Content-Type": "application/x-www-form-urlencoded"})
    with urllib.request.urlopen(req) as resp:
        body = json.loads(resp.read().decode())
    return body["access_token"]


def api_request(path, method="GET", body=None, token=None):
    if token is None:
        token = get_access_token()
    url = f"{API_BASE}{path}"
    headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
    data = json.dumps(body).encode("utf-8") if body else None
    req = urllib.request.Request(url, data=data, method=method, headers=headers)
    with urllib.request.urlopen(req) as resp:
        return json.loads(resp.read().decode())


def resolve_calendar(name):
    if "@" in name and "." in name:
        # Looks like an email or raw ID; pass through only if it's the primary
        return name if name == PRIMARY_CALENDAR else None
    # "Persönlich" maps to primary
    if name.lower() in ("persönlich", "personal", "primary"):
        return PRIMARY_CALENDAR
    return CALENDAR_MAP.get(name)


def format_datetime(iso_str):
    dt = iso_str.replace("T", " ").replace("Z", "+00:00")
    if len(dt) >= 16:
        return dt[:16]
    return dt


def cmd_list(calendar_name, days=7):
    cal_id = resolve_calendar(calendar_name)
    if cal_id is None:
        friendly = ", ".join(CALENDAR_MAP.keys()) + f", {PRIMARY_CALENDAR}"
        print(f"❌ Kalender '{calendar_name}' nicht gefunden.\n  Verfügbar: {friendly}")
        return
    # Dynamisches Datum (heute, 00:00 in Europe/Vienna)
    tz = datetime.timezone(datetime.timedelta(hours=2))
    today = datetime.datetime.now(tz).strftime('%Y-%m-%dT00:00:00%z')
    today = today[:-2] + ':' + today[-2:]  # +0200 → +02:00
    time_min = urllib.parse.quote(today)
    path = f"/calendars/{urllib.parse.quote(cal_id, safe='')}/events?timeMin={time_min}&maxResults=50&singleEvents=true&orderBy=startTime"
    data = api_request(path)
    print(f"\n=== Events in '{calendar_name}' (nächste {days} Tage) ===\n")
    events = data.get("items", [])
    if not events:
        print("  — keine Termine —\n")
        return
    seen = set()
    for ev in events:
        start = ev.get("start", {})
        date = start.get("dateTime", start.get("date", "?"))
        summary = ev.get("summary", "(kein Titel)")
        key = (date, summary)
        if key in seen:
            continue
        seen.add(key)
        print(f"  {date} | {summary}")
    print()


def cmd_create(calendar_name, summary, start, end, description=""):
    cal_id = resolve_calendar(calendar_name)
    if cal_id is None:
        print(f"❌ Kalender '{calendar_name}' nicht gefunden.")
        return
    body = {
        "summary": summary,
        "start": {"dateTime": start, "timeZone": "Europe/Vienna"},
        "end": {"dateTime": end, "timeZone": "Europe/Vienna"},
    }
    if description:
        body["description"] = description
    path = f"/calendars/{urllib.parse.quote(cal_id, safe='')}/events"
    result = api_request(path, method="POST", body=body)
    print(f"✅ Event erstellt: {result.get('summary')} (ID: {result.get('id')})")


def cmd_delete(calendar_name, event_id):
    cal_id = resolve_calendar(calendar_name)
    if cal_id is None:
        print(f"❌ Kalender '{calendar_name}' nicht gefunden.")
        return
    path = f"/calendars/{urllib.parse.quote(cal_id, safe='')}/events/{event_id}"
    api_request(path, method="DELETE")
    print("🗑️ Event gelöscht.")


if __name__ == "__main__":
    args = sys.argv[1:]
    if not args:
        print(__doc__)
        sys.exit(1)
    cmd = args[0].lower()
    if cmd == "list":
        cmd_list(args[1] if len(args) > 1 else PRIMARY_CALENDAR,
                 int(args[2]) if len(args) > 2 else 7)
    elif cmd == "create":
        cmd_create(args[1], args[2], args[3], args[4], args[5] if len(args) > 5 else "")
    elif cmd == "delete":
        cmd_delete(args[1], args[2])
    else:
        print(__doc__)
        sys.exit(1)
