#!/usr/bin/env python3
"""Update Bonanzo deck slides 4 and 7 with new Ozawa-style illustrations."""
import json
import sys
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload
import io

# Load credentials
with open('/home/clawd/.clawdbot/skills/gmail/tokens/bot-calendar.json') as f:
    token_data = json.load(f)
with open('/home/clawd/.clawdbot/skills/gmail/credentials.json') as f:
    cred_data = json.load(f)['installed']

creds = Credentials(
    token=token_data['token'],
    refresh_token=token_data['refresh_token'],
    token_uri=cred_data['token_uri'],
    client_id=cred_data['client_id'],
    client_secret=cred_data['client_secret'],
    scopes=token_data.get('scopes', ['https://www.googleapis.com/auth/presentations', 'https://www.googleapis.com/auth/drive'])
)

PRES_ID = '1QvQ7WTuOX9ampVhfJLmGSwE8KVTIEbWRsjYs7B9G0jQ'

slides_service = build('slides', 'v1', credentials=creds)
drive_service = build('drive', 'v3', credentials=creds)

def upload_image_to_drive(filepath, filename):
    """Upload image to Drive and return a shareable URL."""
    file_metadata = {
        'name': filename,
        'mimeType': 'image/png'
    }
    media = MediaFileUpload(filepath, mimetype='image/png')
    file = drive_service.files().create(
        body=file_metadata,
        media_body=media,
        fields='id,webContentLink'
    ).execute()
    
    # Make it publicly accessible
    drive_service.permissions().create(
        fileId=file['id'],
        body={'type': 'anyone', 'role': 'reader'}
    ).execute()
    
    file_id = file['id']
    url = f"https://drive.google.com/uc?export=download&id={file_id}"
    print(f"Uploaded {filename} -> {url}")
    return url

def get_slide_ids():
    """Get all slide IDs from the presentation."""
    pres = slides_service.presentations().get(presentationId=PRES_ID).execute()
    slides = pres.get('slides', [])
    print(f"Found {len(slides)} slides")
    for i, slide in enumerate(slides):
        slide_id = slide['objectId']
        # Check for existing images
        images = [e for e in slide.get('pageElements', []) if 'image' in e]
        print(f"  Slide {i+1}: id={slide_id}, images={len(images)}")
        for img in images:
            print(f"    Image: {img['objectId']} @ {img.get('transform', {})}")
    return slides

def add_image_to_slide(slide_id, image_url, x_emu, y_emu, width_emu, height_emu, image_obj_id=None):
    """Add an image to a specific slide."""
    req = {
        'createImage': {
            'url': image_url,
            'elementProperties': {
                'pageObjectId': slide_id,
                'size': {
                    'width': {'magnitude': width_emu, 'unit': 'EMU'},
                    'height': {'magnitude': height_emu, 'unit': 'EMU'}
                },
                'transform': {
                    'scaleX': 1,
                    'scaleY': 1,
                    'translateX': x_emu,
                    'translateY': y_emu,
                    'unit': 'EMU'
                }
            }
        }
    }
    if image_obj_id:
        req['createImage']['objectId'] = image_obj_id
    return req

def emu(inches):
    return int(inches * 914400)

# Get current slide info
slides = get_slide_ids()

if len(slides) < 7:
    print(f"ERROR: Only {len(slides)} slides found, need at least 7")
    sys.exit(1)

# Upload images to Drive
slide4_url = upload_image_to_drive(
    '/home/clawd/workspace/2026-02-03-bonanzo-slide4-ozawa-v4-color.png',
    'bonanzo-slide4-ozawa.png'
)
slide7_url = upload_image_to_drive(
    '/home/clawd/workspace/2026-02-03-bonanzo-slide7-ozawa-v5-portrait.png',
    'bonanzo-slide7-ozawa.png'
)

# Slide dimensions: 10" x 5.625" (standard 16:9)
# Right panel: ~47% width = 4.7", full height
# For slide 4: image on right side, ~4.5" wide, full height
# For slide 7: portrait panel on right, ~2.65" wide (3:4 at 5.625" height = ~4.22" wide), full height

slide4_id = slides[3]['objectId']  # 0-indexed, slide 4
slide7_id = slides[6]['objectId']  # 0-indexed, slide 7

requests = []

# Slide 4: place illustration on right side
# Position: right 47% of slide
requests.append(add_image_to_slide(
    slide4_id,
    slide4_url,
    x_emu=emu(5.3),      # Start at 5.3" from left
    y_emu=emu(0.2),       # Small top margin
    width_emu=emu(4.5),   # ~4.5" wide
    height_emu=emu(5.2)   # Nearly full height
))

# Slide 7: place portrait panel on right
# 3:4 ratio at ~5.2" tall = ~3.9" wide
requests.append(add_image_to_slide(
    slide7_id,
    slide7_url,
    x_emu=emu(5.5),       # Right side
    y_emu=emu(0.0),       # Top aligned
    width_emu=emu(4.2),   # 3:4 width at full height
    height_emu=emu(5.625) # Full slide height
))

# Execute
result = slides_service.presentations().batchUpdate(
    presentationId=PRES_ID,
    body={'requests': requests}
).execute()

print(f"\nDone! Updated slides 4 and 7.")
print(f"Deck: https://docs.google.com/presentation/d/{PRES_ID}/edit")
