#!/usr/bin/env python3
"""Animeer Nano-Banana stills met Veo 3.0-fast (image-to-video).
Retry bij audio-filter; download de clips naar assets/clips/."""
import base64, json, os, sys, time, urllib.request, urllib.error

HERE = os.path.dirname(os.path.abspath(__file__))
KEY = open(os.path.join(HERE, ".env")).read().split("=", 1)[1].strip()
MODEL = "veo-3.0-fast-generate-001"
STILLS = os.path.join(HERE, "assets/stills/nb")
OUT = os.path.join(HERE, "assets/clips")
os.makedirs(OUT, exist_ok=True)

# "no dialogue / ambient only" houdt het audio-filter rustig
SUFFIX = " 3D Pixar animation, no dialogue, no speech, ambient sound only."
SCENES = {
    "02_throw": "The tomato character angrily grabs the beer bottle and throws it off the table, "
                "beer splashing, the banana character recoils in surprise. Energetic motion." + SUFFIX,
    "03_shock": "Close up, the banana character's jaw drops in shock staring at his empty hand, "
                "dramatic slow zoom, candlelight flicker." + SUFFIX,
    "04_grab":  "The banana character pulls the tomato character into a warm happy hug, "
                "glowing love hearts float up, both smile, soft romantic camera move." + SUFFIX,
}

def submit(name, prompt):
    img = base64.b64encode(open(f"{STILLS}/{name}.jpg", "rb").read()).decode()
    url = f"https://generativelanguage.googleapis.com/v1beta/models/{MODEL}:predictLongRunning?key={KEY}"
    body = {"instances": [{"prompt": prompt, "image": {"bytesBase64Encoded": img, "mimeType": "image/jpeg"}}],
            "parameters": {"aspectRatio": "9:16"}}
    req = urllib.request.Request(url, data=json.dumps(body).encode(), headers={"Content-Type": "application/json"})
    return json.load(urllib.request.urlopen(req, timeout=120))["name"]

def poll(op):
    purl = f"https://generativelanguage.googleapis.com/v1beta/{op}?key={KEY}"
    for _ in range(40):
        time.sleep(10)
        r = json.load(urllib.request.urlopen(purl, timeout=60))
        if r.get("done"):
            return r
    return None

def download(uri, dest):
    req = urllib.request.Request(uri + f"&key={KEY}")
    with urllib.request.urlopen(req, timeout=180) as resp:
        data = resp.read()
    open(dest, "wb").write(data)
    return len(data)

for name, prompt in SCENES.items():
    print(f"{name}...")
    ok = False
    for attempt in range(4):
        op = submit(name, prompt)
        r = poll(op)
        if not r:
            print("  timeout, retry"); continue
        if "error" in r:
            print("  err:", r["error"]["message"][:100]); continue
        gv = r["response"]["generateVideoResponse"]
        if gv.get("raiMediaFilteredCount", 0) > 0:
            print(f"  filtered (poging {attempt+1}), retry"); continue
        uri = gv["generatedSamples"][0]["video"]["uri"]
        n = download(uri, f"{OUT}/{name}.mp4")
        print(f"  OK -> {OUT}/{name}.mp4 ({n}b)"); ok = True; break
    if not ok:
        print(f"  !! {name} niet gelukt na 4 pogingen"); sys.exit(1)
print("ALLE CLIPS KLAAR")
