#!/usr/bin/env python3
"""Generate one Salmo 91 video as test."""
from playwright.sync_api import sync_playwright
import subprocess, os, re

VIDEO_DIR = "/home/claw/videos"
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
    
    # Set video options
    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("Enter pressed, waiting for post URL...")
    
    page.wait_for_url("**/post/**", timeout=120000)
    post_id = re.search(r'/post/([a-f0-9-]+)', page.url).group(1)
    print(f"Post: {post_id}")
    
    video_url = None
    for i 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"FOUND! {video_src[:60]}")
            break
        print(f"Waiting... {i*2}s", end="\r")
    
    if video_url:
        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', '-o', f'{VIDEO_DIR}/salmo91_v1_test.mp4', '--max-time', '90', '-b', '/tmp/grok-cookies.txt', video_url], capture_output=True, text=True)
        size = os.path.getsize(f'{VIDEO_DIR}/salmo91_v1_test.mp4') if os.path.exists(f'{VIDEO_DIR}/salmo91_v1_test.mp4') else 0
        print(f"Downloaded: {size//1024}KB")
    else:
        print("FAILED")
    
    cdp.close()