#!/usr/bin/env python3
"""Generate 5 Salmo 91 videos in 16x9 horizontal - final robust version."""
from playwright.sync_api import sync_playwright
import subprocess, os, re

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

PROMPTS = [
    "Person walking through dark valley surrounded by giant rocky mountains, divine light breaking through clouds from above, cinematic 16x9 wide shot, moody atmospheric lighting",
    
    "Ancient biblical warrior standing on mountain peak arms raised toward dramatic stormy sky, lightning bolts in background, epic cinematic 16x9 landscape photography",
    
    "Solitary figure in white garment standing in peaceful garden with morning sun rays streaming through trees, butterflies and soft golden light, cinematic 16x9",
    
    "Person sleeping peacefully in cozy bed while guardian angel with wings stands watch nearby, soft moonlight through window, warm cozy bedroom scene, cinematic 16x9",
    
    "Elderly wise man reading ancient book in candlelit stone library, dramatic shadows and warm golden light, cinematic 16x9 portrait photography style"
]

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 wait_for_post_url(page, timeout=120):
    for _ in range(timeout // 1500):
        page.wait_for_timeout(1500)
        m = re.search(r'/post/([a-f0-9-]+)', page.url)
        if m:
            return m.group(1)
    return None

def wait_for_video(page, timeout=80):
    for _ in range(timeout // 2000):
        page.wait_for_timeout(2000)
        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:
            return video_src
        print(".", end="", flush=True)
    return None

def generate_one_video(page, prompt):
    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")
    
    post_id = wait_for_post_url(page, timeout=120000)
    if not post_id:
        return None, None
    
    video_url = wait_for_video(page)
    return video_url, post_id

def download_and_upload(page, video_url, out_file, drive_id):
    cookies = page.context.cookies(['https://grok.com', 'https://assets.grok.com'])
    with open('/tmp/grok-cookies.txt', 'w') as f:
        for c in cookies:
            for domain in ['.assets.grok.com', '.grok.com']:
                f.write(f'{domain}\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', '/tmp/grok-cookies.txt',
        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:
        if os.path.exists(out_file):
            os.remove(out_file)
        return False
    
    page.goto(f"https://drive.google.com/drive/folders/{drive_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([out_file])
    page.wait_for_timeout(8000)
    return True

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
        out_file = f"{VIDEO_DIR}/salmo91_v{num}_16x9.mp4"
        print(f"\n=== Salmo 91 v{num} ===")
        
        page = ctx.new_page()
        video_url, post_id = generate_one_video(page, prompt)
        
        if not video_url or not post_id:
            print("  FAILED: could not generate")
            page.close()
            continue
        
        print(f"  Post: {post_id}")
        
        if download_and_upload(page, video_url, out_file, DRIVE_FOLDER_ID):
            print(f"  ✅ Uploaded Salmo 91 v{num}")
        else:
            print("  FAILED at download/upload")
        
        page.close()
    
    print("\n=== Done ===")
    for f in sorted(os.listdir(VIDEO_DIR)):
        if f.startswith('salmo91_v') and f.endswith('_16x9.mp4'):
            print(f"  {f}: {os.path.getsize(VIDEO_DIR+'/'+f)//1024}KB")
    
    cdp.close()