#!/usr/bin/env python3

import json
import os
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload

# Constants
PRESENTATION_ID = "1H0gtkiFYcWKWMMbSpYeW2QuMlxSccmW_qYfeYNiNb2E"
SLIDE_ID = "g3cb03ddc076_0_47"
EXISTING_IMAGE_IDS = ["g3cb03ddc076_0_53", "g3cb03ddc076_0_54"]

# Image files and their target positions
IMAGES = [
    {
        "file_path": "/root/.openclaw/workspace/phat-deck-images/chart_ceiling_v3.png",
        "name": "chart_ceiling_v3.png",
        "x": 4901226,  # EMU
        "y": 65531,    # EMU
        "width": 4188175,   # EMU
        "height": 2500000   # EMU
    },
    {
        "file_path": "/root/.openclaw/workspace/phat-deck-images/chart_repeat_v3.png", 
        "name": "chart_repeat_v3.png",
        "x": 4901226,  # EMU
        "y": 2600000,  # EMU
        "width": 4188175,   # EMU
        "height": 2500000   # EMU
    }
]

def load_credentials():
    """Load Google API credentials from the token file."""
    token_path = "/root/.openclaw/workspace/google-auth/token.json"
    
    with open(token_path, 'r') as f:
        token_data = json.load(f)
    
    creds = Credentials(
        token=token_data['token'],
        refresh_token=token_data.get('refresh_token'),
        token_uri=token_data['token_uri'],
        client_id=token_data['client_id'],
        client_secret=token_data['client_secret']
    )
    
    return creds

def upload_image_to_drive(drive_service, image_info):
    """Upload an image to Google Drive and make it publicly accessible."""
    print(f"Uploading {image_info['name']} to Google Drive...")
    
    # Upload the file
    file_metadata = {'name': image_info['name']}
    media = MediaFileUpload(image_info['file_path'], mimetype='image/png')
    
    file = drive_service.files().create(
        body=file_metadata,
        media_body=media,
        fields='id'
    ).execute()
    
    file_id = file.get('id')
    print(f"File uploaded with ID: {file_id}")
    
    # Make the file publicly readable
    permission = {
        'type': 'anyone',
        'role': 'reader'
    }
    drive_service.permissions().create(
        fileId=file_id,
        body=permission
    ).execute()
    
    print(f"File made public: {file_id}")
    
    # Return the public URL
    public_url = f"https://drive.google.com/uc?id={file_id}"
    return public_url

def delete_existing_images(slides_service):
    """Delete the existing images from the slide."""
    print("Deleting existing images...")
    
    requests = []
    for image_id in EXISTING_IMAGE_IDS:
        requests.append({
            'deleteObject': {
                'objectId': image_id
            }
        })
    
    body = {'requests': requests}
    
    slides_service.presentations().batchUpdate(
        presentationId=PRESENTATION_ID,
        body=body
    ).execute()
    
    print(f"Deleted {len(EXISTING_IMAGE_IDS)} existing images")

def insert_new_images(slides_service, image_urls):
    """Insert the new images into the slide."""
    print("Inserting new images...")
    
    requests = []
    
    for i, image_info in enumerate(IMAGES):
        requests.append({
            'createImage': {
                'objectId': f'new_chart_image_{i+1}',
                'url': image_urls[i],
                'elementProperties': {
                    'pageObjectId': SLIDE_ID,
                    'size': {
                        'width': {'magnitude': image_info['width'], 'unit': 'EMU'},
                        'height': {'magnitude': image_info['height'], 'unit': 'EMU'}
                    },
                    'transform': {
                        'scaleX': 1.0,
                        'scaleY': 1.0,
                        'translateX': image_info['x'],
                        'translateY': image_info['y'],
                        'unit': 'EMU'
                    }
                }
            }
        })
    
    body = {'requests': requests}
    
    result = slides_service.presentations().batchUpdate(
        presentationId=PRESENTATION_ID,
        body=body
    ).execute()
    
    print(f"Inserted {len(IMAGES)} new images")
    return result

def main():
    """Main function to replace the slide images."""
    print("Starting image replacement process...")
    
    # Load credentials
    creds = load_credentials()
    
    # Build the services
    drive_service = build('drive', 'v3', credentials=creds)
    slides_service = build('slides', 'v1', credentials=creds)
    
    try:
        # Step 1: Delete existing images
        delete_existing_images(slides_service)
        
        # Step 2: Upload new images to Drive
        image_urls = []
        for image_info in IMAGES:
            url = upload_image_to_drive(drive_service, image_info)
            image_urls.append(url)
        
        # Step 3: Insert new images into the slide
        result = insert_new_images(slides_service, image_urls)
        
        print("✅ Image replacement completed successfully!")
        print(f"Charts uploaded:")
        print(f"  - Top chart (ceiling): {image_urls[0]}")
        print(f"  - Bottom chart (repeat): {image_urls[1]}")
        
    except Exception as e:
        print(f"❌ Error during image replacement: {str(e)}")
        raise

if __name__ == '__main__':
    main()