#!/usr/bin/env python3
"""Generate one Salmo 91 video - clean working version."""
from playwright.sync_api import sync_playwright
import subprocess, os, re

VIDEO_DIR = "/home/claw/videos"
DRIVE_FOLDER_ID = "1NITLT29n0cqNMuHwEpIDx99EUE0hgLHP"
PROMPT = "Person walking through dark valley surrounded by giant rocky mountains, divine light breaking through clouds from above, cinematic 16x9 wide shot, moody atmospheric lighting"

with sync_playwright() as p:
    cdp = p.chromium.connect_over_cdp("http://localhost:9223")
    ctx = cdp.contexts[0]
    page = ctx.pages[0]
    
    page.goto("https://grok.com/imagine", timeout=30000)
    page.wait_for_timeout(3000)
    
    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
    
    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)
    
    print("Filling prompt...")
    page.locator("div[contenteditable]").first.fill(PROMPT)
    page.wait_for_timeout(300)
    page.keyboard.press("Enter")
    print("Generating...")
    
    # Wait for post URL with polling (works reliably)
    post_id = None
    for _ in range(80):
        page.wait_for_timeout(1500)
        m = re.search(r'/post/([a-f0-9-]+)', page.url)
        if m:
            post_id = m.group(1)
            break
    
    if not post_id:
        print("FAILED: no post URL")
        cdp.close()
        exit(1)
    
    print(f"Post: {post_id}")
    
    # Wait for video src on this page
    video_url = None
    for _ in range(40):
        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("FAILED: no video URL")
        cdp.close()
        exit(1)
    
    # Download
    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')
    
    out_file = f"{VIDEO_DIR}/salmo91_v1_16x9.mp4"
    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"Downloaded: {size//1024}KB")
    
    # Upload
    if size > 100_000:
        page.goto(f"https://drive.google.com/drive/folders/{DRIVE_FOLDER_ID}", timeout=30000)
        page.wait_for_timeout(2000)
        try:
            btn = page.locator('[aria-label="Permitirlas todas"]')
            if btn.count() > 0 and btn.is_visible():
                btn.click()
                page.wait_for_timeout(1000)
        except: pass
        
        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([out_file])
        page.wait_for_timeout(8000)
        print(f"Uploaded to Drive!")
    
    cdp.close()