#!/usr/bin/env python3
"""Integrate approved Slide 9 (Revenue) illustration into Bonanzo deck."""
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/slide9-revenue-ecosystem-v5a.png'

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

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

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'
    ).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 {filename} -> {url}")
    return url

# Get slide IDs
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):
    sid = slide['objectId']
    images = [e for e in slide.get('pageElements', []) if 'image' in e]
    texts = []
    for e in slide.get('pageElements', []):
        if 'shape' in e and 'text' in e.get('shape', {}):
            for tr in e['shape']['text'].get('textElements', []):
                if 'textRun' in tr:
                    texts.append(tr['textRun']['content'].strip())
    title = next((t for t in texts if t), '')[:60]
    print(f"  Slide {i+1}: id={sid}, images={len(images)}, title='{title}'")

# Slide 9 is index 8 (0-based) — but let's verify by looking at what we printed
# The deck has slides numbered 1-14 but not all have illustration briefs
# From the deck copy: Slide 9 = "WHY THE BANK" / from illustration briefs = "Revenue"
# Let's identify by index

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

slide9_id = slides[8]['objectId']  # 0-indexed
print(f"\nTargeting Slide 9 (index 8): {slide9_id}")

# Upload image to Drive
image_url = upload_image_to_drive(IMAGE_PATH, 'bonanzo-slide9-revenue-ozawa.png')

# Place illustration on right side of slide (consistent with other slides)
# Standard 16:9 slide = 10" x 5.625"
requests = [{
    'createImage': {
        'url': image_url,
        'elementProperties': {
            'pageObjectId': slide9_id,
            'size': {
                'width': {'magnitude': emu(4.5), 'unit': 'EMU'},
                'height': {'magnitude': emu(5.2), 'unit': 'EMU'}
            },
            'transform': {
                'scaleX': 1,
                'scaleY': 1,
                'translateX': emu(5.3),
                'translateY': emu(0.2),
                'unit': 'EMU'
            }
        }
    }
}]

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

print(f"\n✅ Done! Slide 9 updated with revenue illustration.")
print(f"Deck: https://docs.google.com/presentation/d/{PRES_ID}/edit")
