#!/usr/bin/env python3
"""
Complete corrido tumbao video generation pipeline.
1. Generate videos from Grok (10 videos)
2. Download each via Playwright click on Descargar
3. Upload all to Google Drive
"""
from playwright.sync_api import sync_playwright
import subprocess, time, os, re

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

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 accept_cookies(page):
    """Accept cookie consent if visible."""
    try:
        btn = page.locator('[aria-label="Permitirlas todas"]')
        if btn.count() > 0 and btn.is_visible():
            btn.click()
            print("  Cookie consent accepted")
            page.wait_for_timeout(500)
    except Exception as e:
        pass

def set_video_options(page):
    """Set Video, 720p, 10s, 16:9 using CDP JavaScript."""
    page.evaluate("""
        () => {
            // Video radio
            const videoRadio = Array.from(document.querySelectorAll('button[role="radio"]')).find(b => b.textContent.trim() === 'Video');
            if (videoRadio) videoRadio.click();
        }
    """)
    page.wait_for_timeout(300)
    page.evaluate("""
        () => {
            // 720p radio
            const p720 = Array.from(document.querySelectorAll('button[role="radio"]')).find(b => b.textContent.includes('720p'));
            if (p720) p720.click();
        }
    """)
    page.wait_for_timeout(300)
    page.evaluate("""
        () => {
            // 10s radio
            const s10 = Array.from(document.querySelectorAll('button[role="radio"]')).find(b => b.textContent.includes('10s'));
            if (s10) s10.click();
        }
    """)
    page.wait_for_timeout(300)
    page.evaluate("""
        () => {
            // Click Relación de aspecto button
            const aspBtn = Array.from(document.querySelectorAll('button')).find(b => b.textContent.includes('Relación'));
            if (aspBtn) aspBtn.click();
        }
    """)
    page.wait_for_timeout(800)
    page.evaluate("""
        () => {
            // 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)

def download_video(page, post_id, out_file):
    """Navigate to post page and click Descargar to trigger download."""
    page.goto(f"https://grok.com/imagine/post/{post_id}")
    page.wait_for_timeout(3000)
    
    accept_cookies(page)
    
    # Try Descargar button
    dl = page.locator('[aria-label="Descargar"]')
    if dl.count() > 0:
        # Scroll it into view
        page.evaluate("() => { const b = document.querySelector('[aria-label=\"Descargar\"]'); if(b) b.scrollIntoView({block:'center'}); }")
        page.wait_for_timeout(500)
        try:
            dl.first.click(force=True, timeout=5000)
            print("    Clicked Descargar")
            page.wait_for_timeout(6000)
        except Exception as e:
            print(f"    Click error: {e}")
    else:
        print("    No Descargar button found")

def main():
    os.makedirs(VIDEO_DIR, exist_ok=True)
    
    with sync_playwright() as p:
        cdp = p.chromium.connect_over_cdp("http://localhost:9223")
        print("Connected to Chrome via CDP")
        
        ctx = cdp.contexts[0]
        page = ctx.pages[0] if ctx.pages else ctx.new_page()
        
        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 ---")
            
            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, skipping")
                continue
            
            # Navigate to Grok
            page.goto("https://grok.com/imagine")
            page.wait_for_timeout(4000)
            
            accept_cookies(page)
            set_video_options(page)
            
            # Type prompt
            inp = page.locator("div[contenteditable]").first
            inp.fill(prompt)
            page.wait_for_timeout(500)
            
            # Generate
            page.keyboard.press("Enter")
            print(f"  Generating... ({prompt[:50]}...)")
            
            # Wait for post URL (generation creates /post/ URL)
            post_id = None
            for attempt in range(40):
                page.wait_for_timeout(3000)
                if "/post/" in page.url:
                    m = re.search(r'/post/([a-f0-9-]+)', page.url)
                    if m:
                        post_id = m.group(1)
                        break
                print(f"    [{attempt*3}s] waiting... URL={page.url[:60]}", end="\r")
            
            if not post_id:
                # Try extracting from URL anyway
                m = re.search(r'/post/([a-f0-9-]+)', page.url)
                if m:
                    post_id = m.group(1)
            
            if post_id:
                print(f"\n  Post ready: {post_id}")
                download_video(page, post_id, out_file)
            else:
                print(f"\n  Failed to get post ID")
            
            # Small pause between generations
            page.wait_for_timeout(1000)
        
        print("\n\n=== Checking downloaded files ===")
        for f in sorted(os.listdir(VIDEO_DIR)):
            if f.endswith('.mp4') and f.startswith('corrido'):
                sz = os.path.getsize(f"{VIDEO_DIR}/{f}")
                print(f"  {f}: {sz//1024}KB")
        
        # Upload to Drive
        print("\n=== Uploading to Google Drive ===")
        page.goto(f"https://drive.google.com/drive/folders/{DRIVE_FOLDER_ID}")
        page.wait_for_timeout(2000)
        accept_cookies(page)
        
        for num in range(1, 11):
            local_file = f"{VIDEO_DIR}/corrido_tumba_{num:02d}.mp4"
            if os.path.exists(local_file) and os.path.getsize(local_file) > 100_000:
                print(f"  Uploading corrido_tumba_{num:02d}.mp4...")
                
                # Click Nuevo > Subir archivo
                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)
                
                # Set file
                file_input = page.locator("input[type=file]").last
                file_input.set_input_files([local_file])
                page.wait_for_timeout(8000)
                print(f"    ✅ Uploaded")
            else:
                print(f"    ⚠️ Missing: corrido_tumba_{num:02d}.mp4")
        
        print("\n=== ALL DONE ===")
        cdp.close()

if __name__ == "__main__":
    main()