#!/usr/bin/env python3
"""
Complete pipeline for generating corrido tumbao videos from Grok and uploading to Google Drive.
Uses: Playwright (CDP) + curl with browser cookies.
"""
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"
]

COOKIE_JAR = "/tmp/grok-cookies.txt"

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):
    """Set Video, 720p, 10s, 16:9."""
    page.evaluate("""
        () => {
            const videoRadio = Array.from(document.querySelectorAll('button[role="radio"]')).find(b => b.textContent.trim() === 'Video');
            if (videoRadio) videoRadio.click();
        }
    """)
    page.wait_for_timeout(200)
    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(200)
    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(200)
    page.evaluate("""
        () => {
            const aspBtn = Array.from(document.querySelectorAll('button')).find(b => b.textContent.includes('Relación'));
            if (aspBtn) aspBtn.click();
        }
    """)
    page.wait_for_timeout(600)
    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(400)

def generate_video(page, prompt, num):
    """Generate a single video. Returns (success, video_url_or_none, post_id)."""
    out_file = f"{VIDEO_DIR}/corrido_tumba_{num:02d}.mp4"
    
    # Skip if exists
    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, None, None
    
    page.goto("https://grok.com/imagine")
    page.wait_for_timeout(4000)
    accept_cookies(page)
    set_video_options(page)
    
    # Type prompt
    page.locator("div[contenteditable]").first.fill(prompt)
    page.wait_for_timeout(300)
    
    # Generate
    page.keyboard.press("Enter")
    print(f"  Generating...")
    
    # 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
        print(f"  Waiting... {page.url[:50]}", end="\r")
    
    if not post_id:
        print(f"  Failed: no post ID")
        return False, None, None
    
    print(f"  Post: {post_id}")
    
    # Navigate to post page and intercept video URL
    video_url = [None]
    
    def on_response(resp):
        url = resp.url
        if 'assets.grok.com' in url and 'generated_video.mp4' in url:
            video_url[0] = url
    
    page.on('response', on_response)
    page.goto(f"https://grok.com/imagine/post/{post_id}")
    page.wait_for_timeout(5000)
    accept_cookies(page)
    
    # Also trigger video to load
    page.wait_for_timeout(3000)
    
    if not video_url[0]:
        print(f"  Could not capture video URL")
        return False, post_id, None
    
    print(f"  Video URL: {video_url[0][:80]}")
    
    # Download with curl + cookies
    # Write cookie jar
    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:
            f.write('.assets.grok.com\tTRUE\t/\tFALSE\t0\t' + c['name'] + '\t' + c['value'] + '\n')
            f.write('.grok.com\tTRUE\t/\tFALSE\t0\t' + c['name'] + '\t' + c['value'] + '\n')
    
    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[0]
    ], 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"  Downloaded: {size//1024}KB -> {out_file}")
        return True, video_url[0], post_id
    else:
        print(f"  Download failed (size={size})")
        if os.path.exists(out_file):
            os.remove(out_file)
        return False, video_url[0], post_id

def upload_to_drive(page, filename, num):
    """Upload a file to Google Drive."""
    local_file = f"{VIDEO_DIR}/corrido_tumba_{num:02d}.mp4"
    if not os.path.exists(local_file) or os.path.getsize(local_file) < 100_000:
        print(f"  File missing: {local_file}")
        return False
    
    page.goto(f"https://drive.google.com/drive/folders/{DRIVE_FOLDER_ID}")
    page.wait_for_timeout(2000)
    accept_cookies(page)
    
    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)
    
    file_input = page.locator("input[type=file]").last
    file_input.set_input_files([local_file])
    page.wait_for_timeout(8000)
    print(f"  Uploaded {local_file}")
    return True

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()
        
        results = []
        for i, prompt in enumerate(PROMPTS):
            num = i + 1
            print(f"\n=== Video {num}/10 ===")
            
            success, video_url, post_id = generate_video(page, prompt, num)
            results.append((num, success))
            
            if success:
                print(f"  SUCCESS")
            else:
                print(f"  FAILED")
            
            page.wait_for_timeout(1000)
        
        # Upload all successful files
        print("\n\n=== Uploading to Google Drive ===")
        for num, success in results:
            if success:
                upload_to_drive(page, f"corrido_tumba_{num:02d}.mp4", num)
            else:
                print(f"  Skipping {num} (generation failed)")
        
        # Final check
        print("\n=== Final Files ===")
        for f in sorted(os.listdir(VIDEO_DIR)):
            if f.startswith('corrido_tumba_'):
                sz = os.path.getsize(VIDEO_DIR + '/' + f)
                print(f"  {f}: {sz//1024}KB")
        
        print("\n=== ALL DONE ===")
        cdp.close()

if __name__ == "__main__":
    main()