#!/usr/bin/env python3
"""Debug: generate a video and watch all URL/navigation events."""
from playwright.sync_api import sync_playwright
import subprocess, os, re

VIDEO_DIR = "/home/claw/videos"
PROMPT = "Person walking through dark valley rocky mountains divine light 16x9 horizontal"

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 + 16:9
    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)
    
    # Track ALL navigations with a listener
    nav_events = []
    def on_navigation(frame):
        nav_events.append(f"nav: {frame.url}")
    
    page.on("framenavigated", on_navigation)
    
    print("Pressing Enter...")
    page.keyboard.press("Enter")
    
    # Poll URL every second for 60 seconds
    for i in range(60):
        page.wait_for_timeout(1000)
        current_url = page.url
        print(f"{i}s: {current_url}")
        if '/post/' in current_url:
            post_id = re.search(r'/post/([a-f0-9-]+)', current_url).group(1)
            print(f"POST ID: {post_id}")
            break
    
    print("Nav events captured:")
    for e in nav_events:
        print(f"  {e}")
    
    cdp.close()