#!/usr/bin/env python3
"""Debug the 403 on Veo endpoint."""
import json
import os
import sys
import time
import uuid

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}"

headers = {
    "Origin": "https://labs.google",
    "Referer": "https://labs.google/fx/tools/video-fx",
    "Content-Type": "application/json",
    "Cookie": cookie_str,
}

client = httpx.Client(timeout=60, follow_redirects=True)

# Get token
r = client.get("https://labs.google/fx/api/auth/session", headers=headers)
data = r.json()
access_token = data.get("access_token")
print(f"Token: {access_token[:50]}...")

auth_headers = {**headers, "Authorization": f"Bearer {access_token}"}

# Use the exact same body structure from the captured request
EP = "https://aisandbox-pa.googleapis.com/v1/video:batchAsyncGenerateVideoText"
sid = f";{int(time.time()*1000)}"
scene_id = str(uuid.uuid4())

body = {
    "clientContext": {
        "recaptchaContext": {
            "token": "",
            "applicationType": "RECAPTCHA_APPLICATION_TYPE_WEB",
        },
        "sessionId": sid,
        "projectId": "eefb63cd-ef47-4c92-ade5-fd427a029deb",
        "tool": "PINHOLE",
    },
    "requests": [
        {
            "aspectRatio": "VIDEO_ASPECT_RATIO_LANDSCAPE",
            "seed": 42,
            "textInput": {
                "prompt": "A cute orange cat walking on a sunny windowsill",
            },
            "videoModelKey": "veo_3_1_t2v_fast",
            "metadata": {
                "sceneId": scene_id,
            },
        }
    ],
}

print(f"\n--- Test 1: Bearer + Cookie ---")
r = client.post(EP, json=body, headers=auth_headers)
print(f"Status: {r.status_code}")
print(f"Response: {r.text[:500]}")

# Test 2: Try with userPaygateTier (the captured request had it)
print(f"\n--- Test 2: With userPaygateTier ---")
body["clientContext"]["userPaygateTier"] = "PAYGATE_TIER_ONE"
r = client.post(EP, json=body, headers=auth_headers)
print(f"Status: {r.status_code}")
print(f"Response: {r.text[:500]}")

# Test 3: Maybe the issue is that we need the recaptcha token
# The captured request had a real recaptcha token
# Let's try without recaptchaContext entirely
print(f"\n--- Test 3: Without recaptchaContext ---")
body2 = {
    "clientContext": {
        "sessionId": sid,
        "projectId": "eefb63cd-ef47-4c92-ade5-fd427a029deb",
        "tool": "PINHOLE",
        "userPaygateTier": "PAYGATE_TIER_ONE",
    },
    "requests": [
        {
            "aspectRatio": "VIDEO_ASPECT_RATIO_LANDSCAPE",
            "seed": 42,
            "textInput": {
                "prompt": "A cute orange cat walking on a sunny windowsill",
            },
            "videoModelKey": "veo_3_1_t2v_fast",
            "metadata": {
                "sceneId": str(uuid.uuid4()),
            },
        }
    ],
}
r = client.post(EP, json=body2, headers=auth_headers)
print(f"Status: {r.status_code}")
print(f"Response: {r.text[:500]}")

# Test 4: Try with API key like the credits endpoint uses
print(f"\n--- Test 4: With API key ---")
r = client.post(
    EP + "?key=AIzaSyBtrm0o5ab1c-Ec8ZuLcGt3oJAA5VWt3pY",
    json=body2,
    headers=auth_headers,
)
print(f"Status: {r.status_code}")
print(f"Response: {r.text[:500]}")

client.close()
