#!/usr/bin/env python3
"""Update Bonanzo deck slide 7 with piggy bank smash v2 illustration."""
import json
import sys
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload

# 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'
IMAGE_PATH = '/home/clawd/workspace/2026-02-03-bonanzo-slide07-v2b.png'

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

def upload_image_to_drive(filepath, filename):
    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'
    ).execute()
    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 -> {url}")
    return url

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

# Get slide 7 info
pres = slides_service.presentations().get(presentationId=PRES_ID).execute()
slides = pres.get('slides', [])
print(f"Found {len(slides)} slides")

if len(slides) < 7:
    print(f"ERROR: Only {len(slides)} slides")
    sys.exit(1)

slide7 = slides[6]  # 0-indexed
slide7_id = slide7['objectId']
print(f"Slide 7 ID: {slide7_id}")

# Find existing images on slide 7
requests = []
for elem in slide7.get('pageElements', []):
    if 'image' in elem:
        print(f"  Removing existing image: {elem['objectId']}")
        requests.append({'deleteObject': {'objectId': elem['objectId']}})

# Upload new image
image_url = upload_image_to_drive(IMAGE_PATH, 'bonanzo-slide7-piggy-smash-v2.png')

# Add image to slide 7 - right side panel
# 16:9 landscape image on right ~47% of slide
requests.append({
    'createImage': {
        'url': image_url,
        'elementProperties': {
            'pageObjectId': slide7_id,
            'size': {
                'width': {'magnitude': emu(4.7), 'unit': 'EMU'},
                'height': {'magnitude': emu(2.64), 'unit': 'EMU'}  # 16:9 ratio
            },
            'transform': {
                'scaleX': 1, 'scaleY': 1,
                'translateX': emu(5.1),
                'translateY': emu(1.5),  # Centered vertically
                'unit': 'EMU'
            }
        }
    }
})

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

print(f"\nDone! Slide 7 updated with piggy bank smash v2.")
print(f"Deck: https://docs.google.com/presentation/d/{PRES_ID}/edit")
