#!/usr/bin/env python3
"""Upload image to Google Drive and insert it into a Google Slides presentation."""

import json
import sys
import requests

TOKEN_PATH = "/home/clawd/.openclaw/skills/gmail/tokens/bot-calendar.json"
PRESENTATION_ID = "1QvQ7WTuOX9ampVhfJLmGSwE8KVTIEbWRsjYs7B9G0jQ"
IMAGE_PATH = "/home/clawd/workspace/2026-02-03-bonanzo-slide11-compliance-v2.png"

def get_access_token():
    with open(TOKEN_PATH) as f:
        creds = json.load(f)
    resp = requests.post("https://oauth2.googleapis.com/token", data={
        "client_id": creds["client_id"],
        "client_secret": creds["client_secret"],
        "refresh_token": creds["refresh_token"],
        "grant_type": "refresh_token"
    })
    resp.raise_for_status()
    return resp.json()["access_token"]

def get_slide_info(token):
    """Get presentation slides to find Slide 11's object IDs."""
    headers = {"Authorization": f"Bearer {token}"}
    resp = requests.get(
        f"https://slides.googleapis.com/v1/presentations/{PRESENTATION_ID}",
        headers=headers
    )
    if resp.status_code == 403:
        print(f"Slides API 403: {resp.text}")
        print("Trying via Drive API...")
        return None
    resp.raise_for_status()
    return resp.json()

def upload_to_drive(token, file_path):
    """Upload image to Google Drive, make it accessible, return URL."""
    headers = {"Authorization": f"Bearer {token}"}
    
    # Upload file
    metadata = {"name": "bonanzo-slide11-compliance.png", "mimeType": "image/png"}
    
    # Initiate resumable upload
    resp = requests.post(
        "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart",
        headers=headers,
        files={
            "metadata": ("metadata", json.dumps(metadata), "application/json"),
            "file": ("image.png", open(file_path, "rb"), "image/png")
        }
    )
    resp.raise_for_status()
    file_id = resp.json()["id"]
    print(f"Uploaded to Drive: {file_id}")
    
    # Make publicly accessible
    requests.post(
        f"https://www.googleapis.com/drive/v3/files/{file_id}/permissions",
        headers={**headers, "Content-Type": "application/json"},
        json={"role": "reader", "type": "anyone"}
    )
    
    image_url = f"https://drive.google.com/uc?id={file_id}&export=download"
    print(f"Public URL: {image_url}")
    return file_id, image_url

def find_slide_11(presentation):
    """Find the 11th slide and its image placeholder."""
    slides = presentation.get("slides", [])
    if len(slides) < 11:
        print(f"Only {len(slides)} slides found")
        return None, None
    
    slide = slides[10]  # 0-indexed, slide 11
    slide_id = slide["objectId"]
    print(f"Slide 11 ID: {slide_id}")
    
    # Find existing image elements on this slide
    image_id = None
    for element in slide.get("pageElements", []):
        if "image" in element:
            image_id = element["objectId"]
            print(f"Found existing image: {image_id}")
            break
    
    return slide_id, image_id

def replace_image_on_slide(token, slide_id, image_id, image_url):
    """Replace existing image or create new one on the slide."""
    headers = {
        "Authorization": f"Bearer {token}",
        "Content-Type": "application/json"
    }
    
    requests_body = []
    
    if image_id:
        # Delete old image first
        requests_body.append({
            "deleteObject": {"objectId": image_id}
        })
    
    # Create new image covering most of the slide
    # Google Slides dimensions are in EMU (English Metric Units)
    # 1 inch = 914400 EMU, standard slide is 10x7.5 inches
    requests_body.append({
        "createImage": {
            "url": image_url,
            "elementProperties": {
                "pageObjectId": slide_id,
                "size": {
                    "width": {"magnitude": 4572000, "unit": "EMU"},   # 5 inches
                    "height": {"magnitude": 6096000, "unit": "EMU"}   # 6.67 inches (3:4)
                },
                "transform": {
                    "scaleX": 1,
                    "scaleY": 1,
                    "translateX": 457200,   # 0.5 inch from left
                    "translateY": 228600,   # 0.25 inch from top
                    "unit": "EMU"
                }
            }
        }
    })
    
    resp = requests.post(
        f"https://slides.googleapis.com/v1/presentations/{PRESENTATION_ID}:batchUpdate",
        headers=headers,
        json={"requests": requests_body}
    )
    
    if resp.status_code != 200:
        print(f"Slides API error: {resp.status_code} {resp.text}")
        return False
    
    print("✅ Image placed on Slide 11!")
    return True

def main():
    print("Getting access token...")
    token = get_access_token()
    
    print("Reading presentation...")
    pres = get_slide_info(token)
    if not pres:
        print("Cannot access Slides API - may need presentations scope")
        print("Uploading image to Drive anyway for manual placement...")
        file_id, url = upload_to_drive(token, IMAGE_PATH)
        print(f"\nImage uploaded to Drive: https://drive.google.com/file/d/{file_id}")
        print("You can manually insert it into Slide 11")
        return
    
    slide_id, image_id = find_slide_11(pres)
    if not slide_id:
        print("Could not find Slide 11")
        return
    
    print("Uploading image to Drive...")
    file_id, image_url = upload_to_drive(token, IMAGE_PATH)
    
    print("Placing image on Slide 11...")
    success = replace_image_on_slide(token, slide_id, image_id, image_url)
    
    if success:
        print(f"\n✅ Done! Check the deck: https://docs.google.com/presentation/d/{PRESENTATION_ID}")
    else:
        print(f"\nImage is on Drive: https://drive.google.com/file/d/{file_id}")
        print("Manual placement may be needed if Slides API scope is missing")

if __name__ == "__main__":
    main()
