#!/usr/bin/env python3
"""Replace slide 2 image with arm-fixed version."""
import json
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload

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', [])
)

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

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

# Upload fixed image
media = MediaFileUpload('/home/clawd/workspace/2026-02-03-bonanzo-slide2-ozawa-r3.png', mimetype='image/png')
file = drive_service.files().create(body={'name': 'bonanzo-slide2-arms-fixed.png'}, media_body=media, fields='id').execute()
drive_service.permissions().create(fileId=file['id'], body={'type': 'anyone', 'role': 'reader'}).execute()
url = f"https://drive.google.com/uc?export=download&id={file['id']}"

# Remove old image on slide 2
pres = slides_service.presentations().get(presentationId=PRES_ID).execute()
slide2 = pres['slides'][1]
del_reqs = [{'deleteObject': {'objectId': e['objectId']}} for e in slide2.get('pageElements', []) if 'image' in e]
if del_reqs:
    slides_service.presentations().batchUpdate(presentationId=PRES_ID, body={'requests': del_reqs}).execute()

# Add new
slides_service.presentations().batchUpdate(presentationId=PRES_ID, body={'requests': [{
    'createImage': {
        'url': url,
        'elementProperties': {
            'pageObjectId': 'slide02',
            'size': {'width': {'magnitude': emu(4.2), 'unit': 'EMU'}, 'height': {'magnitude': emu(5.625), 'unit': 'EMU'}},
            'transform': {'scaleX': 1, 'scaleY': 1, 'translateX': emu(5.8), 'translateY': 0, 'unit': 'EMU'}
        }
    }
}]}).execute()
print(f"Slide 2 updated. Deck: https://docs.google.com/presentation/d/{PRES_ID}/edit")
