#!/usr/bin/env python3
"""Generate /bug-hunt in lobster puppet world style - 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}"

prompt = """A cinematic photograph of three handmade felt puppet characters in a modern office setting, hunting for software bugs. The puppets are Muppet-style with fleece/felt skin, yarn hair, bead eyes, and hinged mouths. 

The three distinct puppet characters:
1. A nerdy puppet with glasses and a hoodie, crouching and peering at a laptop screen with a magnifying glass
2. A punk puppet with colorful yarn hair and a denim jacket, holding a butterfly net trying to catch glowing digital bugs
3. A detective puppet wearing a tiny felt trench coat and fedora, examining a corkboard covered in code printouts and red string

Small cute glowing bug icons (like tiny neon beetles/insects) float around the scene. The text "/bug-hunt" appears on a computer monitor in the background in a terminal font.

The environment is a real photorealistic modern office/desk setup with warm natural lighting. Shallow depth of field. The puppets have a warm, humorous, handmade quality — fuzzy felt texture, visible fabric seams, matte non-reflective surfaces. Color palette: warm earth tones with pops of saturated color. Soft diffused lighting. Wide 16:9 cinematic composition."""

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(f"Generating with {model}...")
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[:500]}")
    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-puppet-imagen-{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)")

if not result.get("predictions"):
    print("No predictions in response")
    print(json.dumps(result, indent=2)[:500])
    sys.exit(1)
