#!/usr/bin/env python3
"""The Catch - 3 characters: hunter, skeptic, referee. Wide banner ratio."""

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 wide photograph of a bright modern startup office. Exactly THREE life-size handmade felt Muppet-style puppet characters, human-sized, standing at full height in a modern office environment.

CHARACTER 1 — THE HUNTER (center): Wears a felt trench coat and fedora like a film noir detective. Triumphantly holds up a glass mason jar containing a small fuzzy felt bug creature with big googly eyes. Confident, proud stance. This is the hero of the shot.

CHARACTER 2 — THE SKEPTIC (left): A developer in a black hoodie with arms crossed, leaning against a desk. Expression is doubtful, one eyebrow raised, not convinced the bug is actually caught. Skeptical body language — maybe tilting their head sideways examining the jar from a distance.

CHARACTER 3 — THE REFEREE (right): Wears a black and white vertically striped referee shirt and has a silver whistle around their neck. One arm raised making an official call/signal. They're the one who determines if the bug is valid. Authoritative but fun stance.

All three puppets are HUMAN-SIZED — standing on the floor at adult height. They have felt/fleece skin, yarn hair in different bright colors, bead eyes, Muppet-style hinged mouths. Real fabric clothing at human scale.

The fuzzy bug in the jar is round, fluffy, caterpillar-like with big innocent googly eyes and tiny antennae.

Modern office background: standing desks, monitors, sticky notes, warm golden afternoon light from windows. The composition is WIDE — approximately 3:1 aspect ratio, like a movie banner. Generous negative space above the characters for text overlay. Shallow depth of field. Cinematic lighting."""

# Generate at wider ratio - use 16:9 and we'll crop, or try the widest available
payload = {
    "instances": [{"prompt": prompt}],
    "parameters": {
        "sampleCount": 4,
        "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 3-character catch (hunter/skeptic/referee)...")
try:
    with urllib.request.urlopen(req, timeout=180) 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-final-{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)")

print("Done!")
