#!/usr/bin/env python3
"""Verify PHAT CEO deck in Google Slides."""
import json, os, sys
from urllib.request import Request, urlopen
from urllib.error import HTTPError

# Auth paths for this workspace
CREDS_PATH = "/root/.openclaw/workspace/google-auth/credentials.json"
TOKEN_PATH = "/root/.openclaw/workspace/google-auth/token.json"
PHAT_DECK_ID = "1H0gtkiFYcWKWMMbSpYeW2QuMlxSccmW_qYfeYNiNb2E"

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 extract_slide_content(slide):
    """Extract text content and basic styling info from a slide."""
    elements = slide.get("pageElements", [])
    content = {"texts": [], "styles": []}
    
    for el in elements:
        shape = el.get("shape", {})
        text_obj = shape.get("text", {})
        
        for text_elem in text_obj.get("textElements", []):
            text_run = text_elem.get("textRun", {})
            text_content = text_run.get("content", "").strip()
            
            if text_content:
                style = text_run.get("style", {})
                font_size = style.get("fontSize", {}).get("magnitude", 0)
                font_family = style.get("fontFamily", "")
                bold = style.get("bold", False)
                color = style.get("foregroundColor", {}).get("opaqueColor", {})
                
                content["texts"].append(text_content)
                content["styles"].append({
                    "text": text_content,
                    "font_size": font_size,
                    "font_family": font_family,
                    "bold": bold,
                    "color": color
                })
    
    return content

def main():
    try:
        client, token = load_config()
        print("Refreshing access token...")
        access_token = refresh_access_token(client, token)
        print("✅ Got access token")
        
        print(f"\nFetching PHAT presentation...")
        pres = slides_api(access_token, PHAT_DECK_ID)
        
        if not pres:
            print("❌ Failed to access PHAT deck")
            return False
        
        title = pres.get('title', 'Untitled')
        slides = pres.get("slides", [])
        slide_count = len(slides)
        
        print(f"✅ Title: {title}")
        print(f"✅ Slide count: {slide_count}")
        
        # Check each slide
        print("\nAnalyzing slides:")
        verification_results = []
        
        for i, slide in enumerate(slides, 1):
            print(f"Slide {i}:")
            content = extract_slide_content(slide)
            
            # Basic content check
            if content["texts"]:
                all_text = "\n".join(content["texts"])
                print(f"  Content preview: {all_text[:100]}...")
            else:
                print("  ❌ No text content found")
            
            # Style analysis
            styles = content["styles"]
            for style in styles:
                text_preview = style["text"][:50]
                print(f"    '{text_preview}' - {style['font_family']} {style['font_size']}pt {'bold' if style['bold'] else ''}")
        
        return True
        
    except Exception as e:
        print(f"Error: {e}")
        return False

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)