#!/usr/bin/env python3
"""Nieuwe verhaallijn (reversal): banaan schopt tomaat eruit en kiest het bier.
Gebruikt bestaande hero (01_setup.jpg) als referentie voor consistentie."""
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()
MODEL = "gemini-2.5-flash-image"
URL = f"https://generativelanguage.googleapis.com/v1beta/models/{MODEL}: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 with cartoon face "
        "and muscular arms, black tank top. TOMATO-WOMAN: red tomato with cartoon face, green leaf "
        "hair, red dress. They are fruit, not humans. 3D Pixar render, candlelit restaurant, night "
        "city skyline window, warm bokeh, vertical 9:16.")

SCENES = {
    "r2_argue":  "The tomato-woman angrily points at the banana-man's beer bottle scolding him, "
                 "the banana-man frowns and clutches his beer protectively.",
    "r3_kickout":"The banana-man stands up furious and points firmly toward the exit door, "
                 "the tomato-woman storms away offended toward the door.",
    "r4_bottle": "The banana-man sits back alone, relaxed and grinning, happily raising his beer "
                 "bottle in triumph, the chair beside him empty.",
}

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