#!/usr/bin/env python3 """Verify Google Calendar OAuth credentials are valid. Reads GOOGLE_CREDS_PATH env var (or falls back to secrets/google_creds.json), loads the authorized_user credentials, and does one cheap API probe (calendarList.list(maxResults=1)). Output: single JSON object on stdout: {"ok": true, "message": "..."} {"ok": false, "message": "..."} """ from __future__ import annotations import json import os import sys def main() -> None: creds_path = os.environ.get( "GOOGLE_CREDS_PATH", os.path.join(os.path.dirname(__file__), "secrets", "google_creds.json"), ) if not os.path.exists(creds_path): _fail(f"Credentials file not found at {creds_path}. Run gcal_oauth_setup.py first.") return try: from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials from googleapiclient.discovery import build except ImportError as e: _fail(f"Missing dependencies: {e}. Install google-api-python-client and google-auth.") return try: creds = Credentials.from_authorized_user_file( creds_path, ["https://www.googleapis.com/auth/calendar"], ) except Exception as e: _fail(f"Failed to load credentials: {e}") return if creds.expired and creds.refresh_token: try: creds.refresh(Request()) with open(creds_path, "w") as f: f.write(creds.to_json()) except Exception as e: _fail(f"Token refresh failed: {e}. Re-run gcal_oauth_setup.py.") return try: service = build("calendar", "v3", credentials=creds) result = service.calendarList().list(maxResults=1).execute() items = result.get("items", []) primary = next((c for c in items if c.get("primary")), None) account = primary.get("id", "?") if primary else "?" _ok(f"Google Calendar credentials valid. Account: {account}") except Exception as e: _fail(f"API probe failed: {e}") def _ok(message: str) -> None: json.dump({"ok": True, "message": message}, sys.stdout) def _fail(message: str) -> None: json.dump({"ok": False, "message": message}, sys.stdout) sys.exit(1) if __name__ == "__main__": main()