#!/usr/bin/env python3
"""The Catch - human-sized puppets in chairs, not miniatures on desks."""

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

prompt = """Cinematic photograph of a bright modern startup office. Three LIFE-SIZE handmade felt Muppet-style puppet characters — they are HUMAN-SIZED, sitting in real office chairs and standing at full height like adult people. They are NOT miniatures or toys.

The scene: a spontaneous celebration moment. The detective puppet (full-size, wearing a felt trench coat and fedora) stands triumphantly holding up a glass mason jar at eye level. Inside the jar is a small round fuzzy furry felt BUG creature with big googly eyes and tiny antennae, pressing against the glass looking bewildered.

A dev puppet in a black oversized hoodie with headphones around their neck has jumped up from their office chair, fist pumping the air. Another dev puppet wearing a beanie and vintage band t-shirt leans back in their ergonomic office chair, arms behind their head, grinning in satisfaction.

The puppets are FULL HUMAN SIZE — their heads are at normal human head height, they sit in chairs like people, their feet touch the floor. They have felt/fleece skin, yarn hair in bright colors, bead eyes, Muppet-style hinged mouths. Clothing is real fabric at human scale.

The office has standing desks with sticker-covered laptops, energy drink cans, sticky notes on monitors, tangled cables. Late afternoon golden window light. The upper portion of the image has lighter wall/ceiling space for text overlay. Shallow depth of field. Wide 16:9 cinematic composition. The feeling is candid — like someone snapped a photo of the exact triumphant moment."""

payload = {
    "instances": [{"prompt": prompt}],
    "parameters": {
        "sampleCount": 2,
        "aspectRatio": "16:9",
        "personGeneration": "allow_adult"
    }
}

data = json.dumps(payload).encode()
req = urllib.request.Request(url, data=data, headers={"Content-Type": "application/json"})

print("Generating the-catch v3 (human-sized puppets)...")
try:
    with urllib.request.urlopen(req, timeout=120) as resp:
        result = json.loads(resp.read())
except urllib.error.HTTPError as e:
    print(f"HTTP {e.code}: {e.read().decode()[:300]}")
    sys.exit(1)

for i, pred in enumerate(result.get("predictions", [])):
    if "bytesBase64Encoded" in pred:
        img_data = base64.b64decode(pred["bytesBase64Encoded"])
        out = f"/root/.openclaw/workspace/output/bug-hunt-catch-v3-{i+1}.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)")
