#!/usr/bin/env python3
"""Generate 10 corrido tumbao videos with upscale (720p real) and upload to Drive."""
from playwright.sync_api import sync_playwright
import subprocess, 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):
    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 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 fill_with_js(page, text):
    escaped = text.replace('\\', '\\\\').replace('"', '\\"')
    page.evaluate(f"""
        () => {{
            const el = document.querySelector('div[contenteditable]');
            if (!el) return;
            el.focus();
            el.textContent = "{escaped}";
            el.dispatchEvent(new InputEvent('input', {{ bubbles: true, cancelable: true }}));
        }}
    """)

def generate_and_download_upscale(page, prompt, num):
    out_file = f"{VIDEO_DIR}/corrido_tumba_{num:02d}_720p.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", timeout=60000)
    page.wait_for_timeout(3000)
    accept_cookies(page)
    set_video_options(page)
    fill_with_js(page, prompt)
    page.wait_for_timeout(500)
    page.keyboard.press("Enter")
    
    # Wait for post URL
    post_id = None
    for _ in range(80):
        page.wait_for_timeout(1500)
        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}")
    
    # Wait for original video to be ready
    for _ in range(40):
        page.wait_for_timeout(2000)
        video_src = page.evaluate("document.querySelector('video')?.src || ''")
        if video_src and ('assets.grok.com' in video_src or 'imagine-public' in video_src):
            print(f"  Video ready!")
            break
        print(".", end="", flush=True)
    
    # Click Aumentar resolución
    print("  Upscaling...")
    page.locator('[aria-label="Más opciones"]').click()
    page.wait_for_timeout(500)
    page.evaluate("""
        () => {
            const btns = Array.from(document.querySelectorAll('button'));
            const ar = btns.find(b => b.innerText.includes('Aumentar resolución'));
            if (ar) ar.click();
        }
    """)
    
    # Wait for upscaled video to appear (second video element with higher res)
    upscaled = None
    for _ in range(30):
        page.wait_for_timeout(2000)
        videos = page.evaluate("""
            () => Array.from(document.querySelectorAll('video')).map(v => ({
                src: v.src,
                w: v.videoWidth,
                h: v.videoHeight
            }))
        """)
        # Find the video that's larger than original (752x416)
        for v in videos:
            if v['w'] > 800 or v['h'] > 500:
                upscaled = v['src']
                print(f"  Upscaled video: {v['w']}x{v['h']}")
                break
        if upscaled:
            break
        print(".", end="", flush=True)
    
    if not upscaled:
        # Fallback to original
        upscaled = page.evaluate("document.querySelector('video')?.src || ''")
        print(f"  Using original video")
    
    if not upscaled:
        print(f"  FAILED: no video URL")
        return False
    
    # Export cookies and download
    cookies = page.context.cookies(['https://grok.com', 'https://assets.grok.com', 'https://imagine-public.x.ai'])
    with open('/tmp/grok-cookies.txt', 'w') as f:
        for c in cookies:
            for domain in ['.imagine-public.x.ai', '.assets.grok.com', '.grok.com']:
                f.write(f'{domain}\tTRUE\t/\tFALSE\t0\t{c["name"]}\t{c["value"]}\n')
    
    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', '/tmp/grok-cookies.txt',
        upscaled
    ], capture_output=True, text=True)
    
    size = os.path.getsize(out_file) if os.path.exists(out_file) else 0
    print(f"  Downloaded: {size//1024}KB")
    
    if size < 100_000:
        if os.path.exists(out_file): os.remove(out_file)
        return False
    
    return True

def upload_to_drive(page, local_path):
    page.goto(f"https://drive.google.com/drive/folders/{DRIVE_FOLDER_ID}", timeout=30000)
    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)
    page.locator("input[type=file]").last.set_input_files([local_path])
    page.wait_for_timeout(8000)
    print(f"  Uploaded!")

with sync_playwright() as p:
    cdp = p.chromium.connect_over_cdp("http://localhost:9223")
    ctx = cdp.contexts[0]
    
    for i, prompt in enumerate(PROMPTS):
        num = i + 1
        print(f"\n=== Corrido {num}/10 ===")
        
        page = ctx.new_page()
        
        if generate_and_download_upscale(page, prompt, num):
            # Upload to Drive
            upload_to_drive(page, f"{VIDEO_DIR}/corrido_tumba_{num:02d}_720p.mp4")
            print(f"  ✅ Done!")
        else:
            print(f"  FAILED")
        
        page.close()
    
    print("\n=== Done ===")
    for f in sorted(os.listdir(VIDEO_DIR)):
        if f.startswith('corrido_tumba_') and '720p' in f:
            print(f"  {f}: {os.path.getsize(VIDEO_DIR+'/'+f)//1024}KB")
    
    cdp.close()