#!/usr/bin/env python3
"""
Complete pipeline for generating corrido tumbao videos from Grok.
Uses: Playwright CDP for generation + URL capture, curl + cookies for download.
"""
from playwright.sync_api import sync_playwright
import subprocess, time, os, re

VIDEO_DIR = "/home/claw/videos"
DRIVE_FOLDER_ID = "1NITLT29n0cqNMuHwEpIDx99EUE0hgLHP"
COOKIE_JAR = "/tmp/grok-cookies.txt"

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):
    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

def set_video_options(page):
    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 p720 = Array.from(document.querySelectorAll('button[role="radio"]')).find(b => b.textContent.includes('720p'));
            if (p720) p720.click();
        }
    """)
    page.wait_for_timeout(150)
    page.evaluate("""
        () => {
            const s10 = Array.from(document.querySelectorAll('button[role="radio"]')).find(b => b.textContent.includes('10s'));
            if (s10) s10.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)

def generate_and_download(page, prompt, num):
    """Generate a video and download it. Returns True on success."""
    out_file = f"{VIDEO_DIR}/corrido_tumba_{num:02d}.mp4"
    
    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)")
        return True
    
    page.goto("https://grok.com/imagine")
    page.wait_for_timeout(4000)
    accept_cookies(page)
    set_video_options(page)
    
    page.locator("div[contenteditable]").first.fill(prompt)
    page.wait_for_timeout(300)
    page.keyboard.press("Enter")
    print(f"  Generating... (prompt: {prompt[:50]}...)")
    
    # Wait for post URL
    post_id = None
    for _ in range(40):
        page.wait_for_timeout(3000)
        m = re.search(r'/post/([a-f0-9-]+)', page.url)
        if m:
            post_id = m.group(1)
            break
    
    if not post_id:
        print(f"  FAILED: no post URL")
        return False
    
    print(f"  Post: {post_id}")
    
    # Navigate to post page and wait for video element to load
    page.on('response', lambda r: None)  # clear previous
    video_url = None
    
    def capture_response(resp):
        nonlocal video_url
        url = resp.url
        # Look specifically for the generated_video.mp4 from assets.grok.com
        if 'assets.grok.com' in url and 'generated_video.mp4' in url:
            video_url = url
            print(f"  Captured: {url[:80]}")
    
    page.on('response', capture_response)
    
    page.goto(f"https://grok.com/imagine/post/{post_id}")
    page.wait_for_timeout(2000)
    accept_cookies(page)
    
    # Wait for the video element to have a src with the post_id
    for _ in range(20):
        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 src: {video_src[:80]}")
            break
        page.wait_for_timeout(2000)
        print(f"  Waiting for video src... ({_ * 2}s)", end="\r")
    
    if not video_url:
        # Try getting it from the video element anyway
        video_src = page.evaluate("document.querySelector('video')?.src || ''")
        if video_src and 'mp4' in video_src:
            video_url = video_src
            print(f"  Using video src: {video_src[:80]}")
    
    if not video_url:
        print(f"  FAILED: no video URL captured")
        return False
    
    # Write cookies
    cookies = page.context.cookies(['https://grok.com', 'https://assets.grok.com', 'https://imagine-public.x.ai'])
    with open(COOKIE_JAR, 'w') as f:
        for c in cookies:
            for domain in ['.assets.grok.com', '.grok.com', '.x.ai']:
                f.write(f'{domain}\tTRUE\t/\tFALSE\t0\t{c["name"]}\t{c["value"]}\n')
    
    # Download
    print(f"  Downloading...")
    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', COOKIE_JAR,
        video_url
    ], capture_output=True, text=True)
    
    size = os.path.getsize(out_file) if os.path.exists(out_file) else 0
    if size > 100_000:
        print(f"  SUCCESS: {size//1024}KB -> {out_file}")
        return True
    else:
        print(f"  FAILED: size={size}")
        if os.path.exists(out_file):
            os.remove(out_file)
        return False

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")
        ctx = cdp.contexts[0]
        page = ctx.pages[0] if ctx.pages else ctx.new_page()
        
        for i, prompt in enumerate(PROMPTS):
            num = i + 1
            print(f"\n=== Video {num}/10 ===")
            success = generate_and_download(page, prompt, num)
            page.wait_for_timeout(500)
        
        # Upload to Drive
        print("\n\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 = f"{VIDEO_DIR}/corrido_tumba_{num:02d}.mp4"
            if os.path.exists(local) and os.path.getsize(local) > 100_000:
                print(f"  Uploading {num}/10...")
                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([local])
                page.wait_for_timeout(8000)
                print(f"  ✅ Uploaded video {num}")
        
        print("\n=== Done ===")
        for f in sorted(os.listdir(VIDEO_DIR)):
            if f.startswith('corrido_tumba_'):
                print(f"  {f}: {os.path.getsize(VIDEO_DIR+'/'+f)//1024}KB")
        
        cdp.close()

if __name__ == "__main__":
    main()