#!/usr/bin/env python3
"""Intercept fetch() calls to aisandbox by injecting JS into the Flow page."""
import json
import os
import sys
import time
from dotenv import load_dotenv
load_dotenv()
from playwright.sync_api import sync_playwright

s = os.getenv("GOOGLE_FLOW_SESSION_TOKEN", "")
c = os.getenv("GOOGLE_FLOW_CSRF_TOKEN", "")

with sync_playwright() as p:
    browser = p.chromium.launch(headless=False)  # visible browser
    context = browser.new_context(
        viewport={"width": 1280, "height": 900},
        locale="en-US",
    )
    
    context.add_cookies([
        {
            "name": "__Secure-next-auth.session-token",
            "value": s,
            "domain": "labs.google",
            "path": "/",
            "secure": True,
            "httpOnly": True,
            "sameSite": "Lax",
        },
        {
            "name": "__Host-next-auth.csrf-token",
            "value": c,
            "domain": "labs.google",
            "path": "/",
            "secure": True,
            "httpOnly": True,
            "sameSite": "Lax",
        },
    ])
    
    page = context.new_page()
    
    # Inject fetch interceptor BEFORE any JS runs
    page.add_init_script("""
        const _origFetch = window.fetch;
        window.__capturedRequests = [];
        window.fetch = async function(...args) {
            const [url, opts] = args;
            const urlStr = typeof url === 'string' ? url : url.url;
            if (urlStr.includes('aisandbox') || urlStr.includes('runVideo')) {
                const body = opts?.body || '';
                let parsed = null;
                try { parsed = JSON.parse(body); } catch(e) {}
                const entry = {url: urlStr, method: opts?.method || 'GET', body: parsed || body};
                window.__capturedRequests.push(entry);
                console.log('INTERCEPTED:', urlStr, JSON.stringify(parsed || body).substring(0, 500));
            }
            return _origFetch.apply(this, args);
        };
    """)
    
    print("Navigating to Flow...")
    page.goto("https://labs.google/fx/tools/video-fx", wait_until="networkidle", timeout=60000)
    print(f"Page: {page.title()}")
    page.wait_for_timeout(3000)
    
    # Close any banner/popup
    try:
        close_btn = page.query_selector("button:has-text('close'), [aria-label='Close']")
        if close_btn and close_btn.is_visible():
            close_btn.click()
            page.wait_for_timeout(1000)
    except:
        pass
    
    # Click "+ Novo projeto" / "+ New project"
    print("Looking for New Project button...")
    new_proj = page.query_selector("button:has-text('Novo projeto'), button:has-text('New project'), [aria-label*='New'], [aria-label*='Novo']")
    if not new_proj:
        # Try finding by text content
        for btn in page.query_selector_all("button"):
            txt = btn.inner_text().strip()
            if "novo" in txt.lower() or "new" in txt.lower() or "add" in txt.lower():
                new_proj = btn
                print(f"  Found: '{txt}'")
                break
    
    if new_proj:
        new_proj.click()
        print("Clicked New Project")
        page.wait_for_timeout(5000)
        page.screenshot(path="veo_after_new_project.png")
        
        # Now look for the prompt input
        print("Looking for prompt input...")
        for sel in ["textarea", "[contenteditable='true']", "[role='textbox']",
                     "input[type='text']", "[data-testid*='prompt']"]:
            els = page.query_selector_all(sel)
            for el in els:
                if el.is_visible():
                    print(f"  Found visible: {sel}")
                    el.click()
                    page.wait_for_timeout(500)
                    page.keyboard.type("A cute orange cat walking on a sunny windowsill, cinematic 4K")
                    print("  Typed prompt!")
                    page.wait_for_timeout(1000)
                    
                    # Find and click generate
                    for btn in page.query_selector_all("button"):
                        if btn.is_visible():
                            t = btn.inner_text().strip().lower()
                            if any(w in t for w in ["generate", "create", "go", "gerar", "criar"]):
                                print(f"  Clicking: '{btn.inner_text().strip()}'")
                                btn.click()
                                break
                    
                    # Wait for the request
                    print("Waiting 20s for API request...")
                    page.wait_for_timeout(20000)
                    break
            else:
                continue
            break
    else:
        print("No New Project button found")
        page.screenshot(path="veo_no_button.png")
    
    # Extract captured requests
    captured = page.evaluate("window.__capturedRequests || []")
    print(f"\n{'='*60}")
    print(f"Captured {len(captured)} requests")
    for req in captured:
        url = req.get("url", "")
        if "runVideo" in url or "SingleClips" in url or "generateVideo" in url:
            print(f"\n*** VIDEO REQUEST ***")
            print(f"URL: {url}")
            print(f"Method: {req.get('method')}")
            print(f"Body:\n{json.dumps(req.get('body'), indent=2)}")
        else:
            print(f"\n{url} ({req.get('method')})")
            body = req.get("body")
            if body:
                print(f"  {json.dumps(body)[:200]}")
    
    # Save all captured
    with open("captured_requests.json", "w") as f:
        json.dump(captured, f, indent=2)
    print("\nSaved to captured_requests.json")
    
    page.screenshot(path="veo_final.png")
    browser.close()
