#!/usr/bin/env python3
"""Download and analyze the Flow JS bundle to extract Veo request body structure."""
import json
import os
import re
import sys
from dotenv import load_dotenv
load_dotenv()
import httpx

s = os.getenv("GOOGLE_FLOW_SESSION_TOKEN", "")
c = os.getenv("GOOGLE_FLOW_CSRF_TOKEN", "")
cookie_str = f"__Secure-next-auth.session-token={s}; __Host-next-auth.csrf-token={c}"

client = httpx.Client(timeout=60, follow_redirects=True)
headers = {"Cookie": cookie_str}

# Get the main page
r = client.get("https://labs.google/fx/tools/video-fx", headers=headers)
js_urls = re.findall(r'src="(/fx/[^"]+\.js)"', r.text)
print(f"Found {len(js_urls)} JS bundles")

# Find the app bundle (largest one usually)
for js_url in js_urls:
    if "_app" in js_url:
        full_url = f"https://labs.google{js_url}"
        print(f"\nDownloading app bundle: {js_url}")
        jr = client.get(full_url)
        text = jr.text
        print(f"Bundle size: {len(text)} chars")
        
        # Save it for analysis
        with open("flow_app_bundle.js", "w") as f:
            f.write(text)
        print("Saved to flow_app_bundle.js")
        
        # Find the function that calls runVideoFxSingleClips
        # Pattern: the function before it that constructs the request
        idx = text.find("'runVideoFxSingleClips'")
        if idx == -1:
            idx = text.find('"runVideoFxSingleClips"')
        if idx == -1:
            # Try obfuscated reference
            for m in re.finditer(r"apiPathName['\"]?\s*:\s*['\"]?([^'\",}]+)", text):
                if 'runVideoFxSingleClips' in text[m.start()-200:m.end()+200]:
                    idx = m.start()
                    break
        
        if idx == -1:
            # Find via the obfuscated string reference
            for m in re.finditer(r"_0x[a-f0-9]+\(0x1d5\)", text):
                ctx = text[max(0,m.start()-1000):m.start()+500]
                if 'apiPathName' in ctx:
                    print(f"\nFound obfuscated ref at {m.start()}")
                    print(ctx[:1500])
                    break
        
        if idx != -1:
            # Get wide context
            ctx = text[max(0,idx-2000):idx+500]
            print(f"\n=== Context around runVideoFxSingleClips (2000 chars before) ===")
            print(ctx)
        
        # Also search for the string array to decode obfuscated values
        # Find the deobfuscation array
        # Search for patterns like 'clipInputs' or 'singleClipInput' in the string table
        video_related_strings = []
        for m in re.finditer(r"'([a-zA-Z]{3,50})'" , text):
            s_val = m.group(1)
            if any(kw in s_val.lower() for kw in ['clip', 'video', 'veo', 'prompt', 'duration', 'resolution']):
                if s_val not in video_related_strings:
                    video_related_strings.append(s_val)
        
        print(f"\n=== Video-related strings in bundle ===")
        for s_val in sorted(set(video_related_strings)):
            print(f"  {s_val}")
        
        break

client.close()
