#!/usr/bin/env python3
from playwright.sync_api import sync_playwright
import sys

files = {
    'psalm91_v3.mp4': '/home/claw/videos/psalm91_v3.mp4',
    'psalm91_v4.mp4': '/home/claw/videos/psalm91_v4.mp4',
    'psalm91_v5.mp4': '/home/claw/videos/psalm91_v5.mp4',
}

with sync_playwright() as p:
    # Connect to existing Chrome via CDP
    cdp = p.chromium.connect_over_cdp('http://localhost:9223')
    print('Connected to Chrome via CDP')
    
    # Get the existing context (the Drive page)
    if not cdp.contexts:
        print('No contexts found')
        sys.exit(1)
    
    ctx = cdp.contexts[0]
    page = ctx.pages[0] if ctx.pages else ctx.new_page()
    
    # Navigate to Drive folder
    page.goto('https://drive.google.com/drive/folders/1NITLT29n0cqNMuHwEpIDx99EUE0hgLHP')
    page.wait_for_timeout(3000)
    print('On Drive page:', page.url)
    
    # Click Nuevo
    page.get_by_role('button', name='Nuevo').click()
    page.wait_for_timeout(1000)
    print('Clicked Nuevo')
    
    # Click Subir archivo
    page.get_by_role('menuitem', name='Subir archivo').click()
    page.wait_for_timeout(1000)
    print('Clicked Subir archivo')
    
    # Now set files on the file input using Playwright
    # Find the file input
    file_input = page.locator('input[type=file]').last
    if file_input.count() > 0:
        print(f'Found file input, setting files: {list(files.values())}')
        file_input.set_input_files(list(files.values()))
        page.wait_for_timeout(5000)
        print('Files set, waiting for upload...')
        page.wait_for_timeout(10000)
    else:
        print('No file input found')
    
    # Check current state
    page.wait_for_timeout(3000)
    content = page.content()
    for fname in files:
        if fname in content:
            print(f'✅ {fname} found on page - upload likely succeeded')
        else:
            print(f'❌ {fname} NOT found on page')
    
    cdp.close()
    print('Done')