#!/usr/bin/env python3
"""Upload missing corrido videos to Google Drive."""
from playwright.sync_api import sync_playwright
import os

VIDEO_DIR = "/home/claw/videos"
DRIVE_FOLDER_ID = "1NITLT29n0cqNMuHwEpIDx99EUE0hgLHP"

# Videos that need uploading (01-10, 02 is failed generation so skip)
TO_UPLOAD = [1, 3, 4, 5, 6, 7, 9, 10]

# Video 02 failed - need to regenerate
GEN_PROMPTS = {
    2: "An artist in a cowboy hat leads a massive crowd in prayer and worship at a huge open-air concert, golden hour lighting, aerial view showing tens of thousands of people, Christian corrido tumbao mood, epic cinematic scene, 16x9 horizontal"
}

def accept_cookies(page):
    try:
        btn = page.locator('[aria-label="Permitirlas todas"]')
        if btn.count() > 0 and btn.is_visible():
            btn.click(timeout=2000)
            page.wait_for_timeout(500)
    except:
        pass

def set_video_options(page):
    page.evaluate("""
        () => {
            const vr = Array.from(document.querySelectorAll('button[role="radio"]')).find(b => b.textContent.trim() === 'Video');
            if (vr) vr.click();
        }
    """)
    page.wait_for_timeout(150)
    page.evaluate("""
        () => {
            const ab = Array.from(document.querySelectorAll('button')).find(b => b.textContent.includes('Relación'));
            if (ab) ab.click();
        }
    """)
    page.wait_for_timeout(500)
    page.evaluate("""
        () => {
            const opt = Array.from(document.querySelectorAll('[role="menuitem"]')).find(m => m.textContent.includes('16:9'));
            if (opt) opt.click();
        }
    """)
    page.wait_for_timeout(300)

def generate_video(page, prompt, num):
    """Generate missing video 02."""
    import re, subprocess
    
    out_file = f"{VIDEO_DIR}/corrido_tumba_{num:02d}.mp4"
    page.goto("https://grok.com/imagine")
    page.wait_for_timeout(4000)
    accept_cookies(page)
    set_video_options(page)
    
    page.locator("div[contenteditable]").first.fill(prompt)
    page.wait_for_timeout(300)
    page.keyboard.press("Enter")
    print(f"  Generating video {num}...")
    
    post_id = None
    for _ in range(40):
        page.wait_for_timeout(3000)
        m = re.search(r'/post/([a-f0-9-]+)', page.url)
        if m:
            post_id = m.group(1)
            break
    
    if not post_id:
        print(f"  FAILED: no post URL")
        return False
    
    print(f"  Post: {post_id}")
    
    # Stay on same page, wait for video
    video_url = None
    for _ in range(30):
        page.wait_for_timeout(2000)
        video_src = page.evaluate("document.querySelector('video')?.src || ''")
        if video_src and 'assets.grok.com' in video_src and 'generated_video.mp4' in video_src:
            video_url = video_src
            print(f"  Video ready!")
            break
        print(f"  Waiting for video...", end="\r")
    
    if not video_url:
        print(f"  FAILED: no video URL")
        return False
    
    cookies = page.context.cookies(['https://grok.com', 'https://assets.grok.com'])
    with open('/tmp/grok-cookies.txt', 'w') as f:
        for c in cookies:
            for domain in ['.assets.grok.com', '.grok.com']:
                f.write(f'{domain}\tTRUE\t/\tFALSE\t0\t{c["name"]}\t{c["value"]}\n')
    
    r = subprocess.run([
        'curl', '-L', '-A',
        'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
        '-o', out_file,
        '--max-time', '120',
        '-b', '/tmp/grok-cookies.txt',
        video_url
    ], capture_output=True, text=True)
    
    size = os.path.getsize(out_file) if os.path.exists(out_file) else 0
    print(f"  {size//1024}KB")
    return size > 100_000

def upload_to_drive(page, local_path):
    filename = os.path.basename(local_path)
    page.goto(f"https://drive.google.com/drive/folders/{DRIVE_FOLDER_ID}")
    page.wait_for_timeout(2000)
    accept_cookies(page)
    
    page.get_by_role("button", name="Nuevo").click()
    page.wait_for_timeout(800)
    page.get_by_role("menuitem", name="Subir archivo").click()
    page.wait_for_timeout(800)
    page.locator("input[type=file]").last.set_input_files([local_path])
    page.wait_for_timeout(8000)
    print(f"  Uploaded: {filename}")

with sync_playwright() as p:
    cdp = p.chromium.connect_over_cdp("http://localhost:9223")
    ctx = cdp.contexts[0]
    page = ctx.pages[0] if ctx.pages else ctx.new_page()
    
    # Regenerate video 02
    print("=== Regenerating video 02 ===")
    if generate_video(page, GEN_PROMPTS[2], 2):
        TO_UPLOAD.append(2)
    
    # Upload missing videos
    print("\n=== Uploading to Drive ===")
    for num in sorted(set(TO_UPLOAD)):
        local = f"{VIDEO_DIR}/corrido_tumba_{num:02d}.mp4"
        if os.path.exists(local) and os.path.getsize(local) > 100_000:
            print(f"  Uploading {num}/10...")
            upload_to_drive(page, local)
        else:
            print(f"  Missing: {local}")
    
    print("\n=== Final state ===")
    for f in sorted(os.listdir(VIDEO_DIR)):
        if f.startswith('corrido_tumba_'):
            print(f"  {f}: {os.path.getsize(VIDEO_DIR+'/'+f)//1024}KB")
    
    cdp.close()