#!/usr/bin/env python3
"""Test Google Slides API access from VPS using bot-calendar token."""
import json, os, sys
from urllib.request import Request, urlopen
from urllib.error import HTTPError

# Paths - work on both Mac and VPS
CREDS_PATH = os.environ.get("CREDS_PATH", "/home/clawd/.clawdbot/skills/gmail/credentials.json")
TOKEN_PATH = os.environ.get("TOKEN_PATH", "/home/clawd/.clawdbot/skills/gmail/tokens/bot-calendar.json")

def load_config():
    with open(CREDS_PATH) as f:
        creds = json.load(f)
    client = creds.get("installed", creds.get("web", {}))
    with open(TOKEN_PATH) as f:
        token = json.load(f)
    return client, token

def refresh_access_token(client, token):
    """Refresh OAuth2 access token."""
    data = (
        f"client_id={client['client_id']}"
        f"&client_secret={client['client_secret']}"
        f"&refresh_token={token['refresh_token']}"
        f"&grant_type=refresh_token"
    ).encode()
    req = Request("https://oauth2.googleapis.com/token", data=data,
                  headers={"Content-Type": "application/x-www-form-urlencoded"})
    resp = urlopen(req, timeout=10)
    result = json.loads(resp.read())
    return result["access_token"]

def slides_api(access_token, presentation_id, endpoint=""):
    url = f"https://slides.googleapis.com/v1/presentations/{presentation_id}{endpoint}"
    req = Request(url, headers={"Authorization": f"Bearer {access_token}"})
    try:
        resp = urlopen(req, timeout=15)
        return json.loads(resp.read())
    except HTTPError as e:
        print(f"ERROR {e.code}: {e.read().decode()[:300]}")
        return None

def main():
    client, token = load_config()
    print("Refreshing access token...", flush=True)
    access_token = refresh_access_token(client, token)
    print("✅ Got access token")
    
    # Test with Bonanzo deck
    BONANZO_ID = "1QvQ7WTuOX9ampVhfJLmGSwE8KVTIEbWRsjYs7B9G0jQ"
    print(f"\nFetching Bonanzo presentation...", flush=True)
    pres = slides_api(access_token, BONANZO_ID)
    
    if pres:
        print(f"✅ Title: {pres.get('title')}")
        slides = pres.get("slides", [])
        print(f"✅ Slides: {len(slides)}")
        for i, slide in enumerate(slides):
            elements = slide.get("pageElements", [])
            texts = []
            for el in elements:
                shape = el.get("shape", {})
                text = shape.get("text", {})
                for run in text.get("textElements", []):
                    tr = run.get("textRun", {})
                    if tr.get("content", "").strip():
                        texts.append(tr["content"].strip())
            preview = " | ".join(texts[:3])[:80]
            print(f"  Slide {i+1}: {preview}")
        
        # Test Connection deck too
        CONNECTION_ID = "1fVxeFZTRx3CLEmQ0jbD_Gfj91RYk7TJB6ktuCIDy9sA"
        print(f"\nFetching Connection presentation...", flush=True)
        pres2 = slides_api(access_token, CONNECTION_ID)
        if pres2:
            print(f"✅ Title: {pres2.get('title')}")
            print(f"✅ Slides: {len(pres2.get('slides', []))}")
        else:
            print("❌ Connection deck not accessible (may need sharing)")
    else:
        print("❌ Failed to access Bonanzo deck")

if __name__ == "__main__":
    main()
