#!/usr/bin/env python3
"""Generate 3 bug-hunt puppet scenes - Imagen 4.0."""

import base64
import json
import os
import sys
import urllib.request

API_KEY = os.environ.get("GEMINI_API_KEY")
model = "imagen-4.0-generate-001"
url = f"https://generativelanguage.googleapis.com/v1beta/models/{model}:predict?key={API_KEY}"

scenes = {
    "war-room": """Cinematic photograph of a modern conference room with floor-to-ceiling windows showing a city skyline at dusk. Three handmade felt Muppet-style puppet characters sit around a sleek concrete table looking stressed — they are young hip developers: one wears an oversized black hoodie with headphones around their neck, one wears a vintage band t-shirt and beanie, one wears a detective-style felt trench coat and fedora (the only non-casual one). They have felt/fleece skin, yarn hair, googly bead eyes, hinged Muppet mouths. The detective puppet stands and points at a wall-mounted monitor. On the table between laptops and coffee cups sits a small fuzzy furry felt BUG creature — like a round fluffy caterpillar with big innocent googly eyes and tiny felt legs, glowing slightly. It looks cute but mischievous. A corkboard behind has printed code snippets connected with red string. The TOP THIRD of the image is intentionally cleaner/darker — negative space suitable for text overlay. Warm natural lighting, shallow depth of field, photorealistic office environment with handmade puppet characters. Wide 16:9 composition.""",

    "evidence-board": """Cinematic photograph of a dark moody office at night, lit by a single warm desk lamp. Three handmade felt Muppet-style puppet characters examine a massive conspiracy-style corkboard on the wall. One puppet wears a grey hoodie and glasses, pointing at the board. One puppet wears a flannel shirt and has colorful yarn hair, holding a coffee cup. One puppet wears a felt trench coat and fedora like a detective, pinning a new card to the board with a pushpin. They have felt/fleece skin, yarn hair, bead eyes, Muppet hinged mouths. The corkboard has index cards, code printouts, and red string connecting them. A small fuzzy furry felt BUG creature — round, fluffy, caterpillar-like with big innocent googly eyes and tiny felt legs — is pinned to the center of the board like evidence. The TOP PORTION of the image has darker negative space suitable for large text overlay. Blue-dark noir atmosphere with warm lamp accent. Photorealistic environment, handmade puppet characters. Wide 16:9.""",

    "the-catch": """Cinematic photograph of a bright warm modern open-plan office. Three handmade felt Muppet-style puppet characters in a moment of celebration. One puppet in a black hoodie stands up from their chair with arms raised. One puppet in a vintage band tee and beanie is pointing excitedly. One puppet in a felt trench coat and fedora holds up a glass mason jar triumphantly — inside the jar is a small fuzzy furry felt BUG creature with big innocent googly eyes looking confused. The bug is round, fluffy, caterpillar-like with tiny felt legs. Desks have laptops, coffee cups, sticky notes. The puppets have felt/fleece skin, yarn hair, bead eyes, Muppet hinged mouths — they look like young hip developers except the detective. The TOP THIRD of the image is cleaner with more negative space — suitable for bold text overlay. Warm natural window lighting, shallow depth of field. Wide 16:9 composition. The energy is triumphant, like ringing a sales gong."""
}

for name, prompt in scenes.items():
    print(f"\nGenerating {name}...")
    payload = {
        "instances": [{"prompt": prompt}],
        "parameters": {
            "sampleCount": 1,
            "aspectRatio": "16:9",
            "personGeneration": "allow_adult"
        }
    }
    data = json.dumps(payload).encode()
    req = urllib.request.Request(url, data=data, headers={"Content-Type": "application/json"})
    try:
        with urllib.request.urlopen(req, timeout=120) as resp:
            result = json.loads(resp.read())
    except urllib.error.HTTPError as e:
        body = e.read().decode()
        print(f"  HTTP {e.code}: {body[:300]}")
        continue

    for pred in result.get("predictions", []):
        if "bytesBase64Encoded" in pred:
            img_data = base64.b64decode(pred["bytesBase64Encoded"])
            out = f"/root/.openclaw/workspace/output/bug-hunt-{name}.png"
            os.makedirs(os.path.dirname(out), exist_ok=True)
            with open(out, "wb") as f:
                f.write(img_data)
            print(f"  Saved: {out} ({len(img_data)} bytes)")

print("\nDone!")
