#!/usr/bin/env python3
"""EPISCHE versie: dramatische hoeken, banaan trapt de tafel om. Hero als referentie."""
import base64, json, os, urllib.request

HERE = os.path.dirname(os.path.abspath(__file__))
KEY = open(os.path.join(HERE, ".env")).read().split("=", 1)[1].strip()
URL = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-image:generateContent?key={KEY}"
STILLS = os.path.join(HERE, "assets/stills/nb")
HERO = open(f"{STILLS}/01_setup.jpg", "rb").read()

LOCK = ("SAME two characters as the reference image. BANANA-MAN: yellow banana, cartoon face, "
        "muscular arms, black tank top. TOMATO-WOMAN: red tomato, cartoon face, green leaf hair, "
        "red dress. Fruit, not humans. CINEMATIC EPIC 3D Pixar render, dramatic moody lighting, "
        "low camera angle, lens flare, candlelit luxury restaurant, night city skyline, "
        "high detail, vertical 9:16.")

SCENES = {
    "e1_intro": "Dramatic wide establishing shot, the banana-man and tomato-woman face each other "
                "across the dinner table with tension in the air, moody cinematic lighting.",
    "e2_throw": "Epic action: the tomato-woman furiously hurls the beer bottle, beer exploding in a "
                "dramatic splash, the banana-man recoils, motion blur, cinematic.",
    "e3_kick":  "Explosive action: the enraged banana-man KICKS the dinner table flipping it over, "
                "plates and food flying everywhere, he points furiously at the door, the tomato-woman "
                "stumbles back shocked, dramatic low angle, dust and debris, epic.",
    "e4_hero":  "Epic hero shot, the banana-man stands alone triumphant raising his beer bottle high "
                "toward the camera, dramatic backlight and lens flare, the empty chair behind him, "
                "cinematic low angle.",
}

def call(prompt):
    parts = [{"text": prompt}, {"inline_data": {"mime_type": "image/jpeg",
              "data": base64.b64encode(HERO).decode()}}]
    body = json.dumps({"contents": [{"parts": parts}],
                       "generationConfig": {"responseModalities": ["IMAGE"],
                                            "imageConfig": {"aspectRatio": "9:16"}}}).encode()
    req = urllib.request.Request(URL, data=body, headers={"Content-Type": "application/json"})
    d = json.load(urllib.request.urlopen(req, timeout=120))
    for p in d["candidates"][0]["content"]["parts"]:
        k = "inlineData" if "inlineData" in p else ("inline_data" if "inline_data" in p else None)
        if k:
            return base64.b64decode(p[k]["data"])
    raise RuntimeError("geen image")

for name, action in SCENES.items():
    print(f"{name}...")
    open(f"{STILLS}/{name}.jpg", "wb").write(call(LOCK + " " + action))
    print("  ok")
print("KLAAR")
