#!/usr/bin/env python3
"""
Generate and download 10 corrido tumbao concert videos from Grok.
Uses Playwright CDP connected to existing Chrome.
Video is generated, then downloaded via the post-page download behavior.
"""
from playwright.sync_api import sync_playwright
import subprocess, time, os, re

VIDEO_DIR = "/home/claw/videos"
DONE_STATE = "/tmp/corridos-state.json"

PROMPTS = [
    "A charismatic singer performs on a massive outdoor stage with purple and gold lights, thousands of fans singing along with raised hands, aerial drone shot revealing the enormous crowd, Christian corrido tumbado aesthetic, cinematic wide shot, 16x9 horizontal format",
    
    "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",
    
    "Lead singer with a guitar performs an emotional corrido while the crowd holds up phone lights creating a sea of stars, dramatic stage lighting in blue and gold, stadium packed with fans, aerial tracking shot, Christian urban worship atmosphere, 16x9 horizontal",
    
    "A Mexican-American corrido artist commands the stage with confetti cannons firing, massive crowd going wild with excitement, aerial drone shot circling the venue, stage with cross-shaped LED screen behind the performer, Christian celebration, cinematic, 16x9 horizontal",
    
    "Street corrido performer sings on a truck bed stage at a massive outdoor festival, crowd of thousands dancing and singing along, sunset sky with dramatic clouds, aerial wide shot of the festival grounds, Christian tumbao vibes, cinematic, 16x9 horizontal",
    
    "Singer in a leather jacket performs an intimate moment during concert while 50,000 people wave lighters and phones, dramatic red and gold stage lighting, aerial pan shot revealing enormous crowd stretching to the horizon, Christian corrido worship, 16x9 horizontal",
    
    "Young corrido artist performs on stage with fog machines and dramatic spotlights, crowd members lifted on shoulders singing every word, aerial drone shot diving through the crowd toward the stage, stadium concert atmosphere, Christian faith celebration, 16x9 horizontal",
    
    "Lead vocalist with full band plays an upbeat Christian corrido, massive dance floor filled with young crowd, confetti and pyrotechnics on stage, aerial establishing shot of packed arena with light shows, tumbao rhythm atmosphere, cinematic, 16x9 horizontal",
    
    "An artist performs an acoustic corrido in a dramatic church converted into concert venue, crowd of thousands with hands raised, dramatic stained glass window as backdrop, aerial shot slowly rotating above the packed floor, Christian worship and celebration, 16x9 horizontal",
    
    "Final concert scene with artist conducting the massive crowd in a spiritual anthem, every phone flashlight on creating ocean of light, dramatic fireworks from stage, aerial wide shot showing city-block-sized crowd, Christian corrido tumbado finale, cinematic grandeur, 16x9 horizontal"
]

def get_post_id_from_url(url):
    """Extract post ID from Grok post URL."""
    m = re.search(r'/post/([a-f0-9-]+)', url)
    return m.group(1) if m else None

def main():
    with sync_playwright() as p:
        cdp = p.chromium.connect_over_cdp("http://localhost:9223")
        print("Connected to Chrome")
        
        ctx = cdp.contexts[0]
        # Use existing page (Grok or Drive)
        if ctx.pages:
            page = ctx.pages[0]
        else:
            page = ctx.new_page()
        
        # Process each prompt
        for i, prompt in enumerate(PROMPTS):
            num = i + 1
            out_file = f"{VIDEO_DIR}/corrido_tumba_{num:02d}.mp4"
            print(f"\n--- Video {num}/10 ---")
            
            # Skip if already downloaded
            if os.path.exists(out_file) and os.path.getsize(out_file) > 100_000:
                print(f"Already exists: {os.path.getsize(out_file)//1024}KB")
                continue
            
            # Navigate to Grok fresh
            page.goto("https://grok.com/imagine")
            page.wait_for_timeout(4000)
            
            # Video should already be selected by default
            # Set 720p and 10s if not already
            try:
                page.get_by_role("radio", name="720p").click(timeout=3000)
                page.wait_for_timeout(200)
                page.get_by_role("radio", name="10s").click(timeout=3000)
                page.wait_for_timeout(200)
            except Exception as e:
                print(f"Radio setup: {e}")
            
            # Set 16:9 aspect ratio via JS (more reliable)
            page.evaluate("""
                (async () => {
                    // Click Relación de aspecto button
                    const btn = Array.from(document.querySelectorAll('button')).find(b => b.textContent.includes('Relación'));
                    if (btn) btn.click();
                    await new Promise(r => setTimeout(r, 1000));
                    // Click 16:9 option
                    const opt = Array.from(document.querySelectorAll('[role=menuitem]')).find(m => m.textContent.includes('16:9'));
                    if (opt) opt.click();
                })()
            """)
            page.wait_for_timeout(500)
            
            # Type prompt
            inp = page.locator("div[contenteditable]").first
            inp.fill(prompt)
            page.wait_for_timeout(500)
            
            # Generate by pressing Enter
            page.keyboard.press("Enter")
            print(f"Generating: {prompt[:60]}...")
            
            # Wait for generation (up to 2 min)
            post_url = None
            for attempt in range(40):  # 40 * 3s = 120s
                page.wait_for_timeout(3000)
                
                # Check for post URL in network requests
                # We need to capture the redirect to /post/ URL
                current_url = page.url
                if "/post/" in current_url:
                    post_url = current_url
                    break
                
                print(f"  [{attempt*3}s] waiting...", end="\r", flush=True)
            
            if not post_url:
                post_url = page.url
                if "/post/" not in post_url:
                    print(f"\nNo post URL found, current URL: {post_url}")
                    continue
            
            post_id = get_post_id_from_url(post_url)
            print(f"\nPost created: {post_id}")
            
            # Navigate to the post page - this should auto-download the video
            page.goto(post_url)
            page.wait_for_timeout(5000)
            
            # Wait for the Descargar button to appear
            dl_found = False
            for attempt in range(20):  # 20 * 3s = 60s
                try:
                    dl_btn = page.get_by_role("button", name="Descargar")
                    if dl_btn.count() > 0:
                        dl_found = True
                        print("Descargar button found!")
                        break
                except:
                    pass
                print(f"  Waiting for download button... {attempt*3}s", end="\r", flush=True)
                page.wait_for_timeout(3000)
            
            if not dl_found:
                print("\nDescargar button never appeared")
                continue
            
            # Set download behavior
            page.evaluate(f"""
                () => {{
                    window.downloadPath = "{VIDEO_DIR}";
                }}
            """)
            
            # Try clicking Descargar
            try:
                dl_btn = page.get_by_role("button", name="Descargar")
                dl_btn.click()
                print("Clicked Descargar")
                page.wait_for_timeout(10000)
            except Exception as e:
                print(f"Click failed: {e}")
            
            # Check for downloaded file
            # The file might be named by the post ID
            potential_files = [
                f"{VIDEO_DIR}/generated_video.mp4",
                f"{VIDEO_DIR}/{post_id}.mp4",
                f"{VIDEO_DIR}/corrido_tumba_{num:02d}.mp4",
            ]
            for pf in potential_files:
                if os.path.exists(pf):
                    size = os.path.getsize(pf)
                    if size > 100_000:
                        # Rename if needed
                        if pf != out_file:
                            os.rename(pf, out_file)
                        print(f"✅ Downloaded: {size//1024}KB -> {out_file}")
                        break
        
        print("\n=== All done ===")
        cdp.close()

if __name__ == "__main__":
    main()