#!/usr/bin/env python3
"""Evidence board with hunter/skeptic/referee characters."""

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 dark moody office at night, lit by a warm vintage desk lamp on the far left. Exactly THREE life-size handmade felt Muppet-style puppet characters — human-sized, standing at full adult height — investigate a large conspiracy-style corkboard covering most of the back wall.

CHARACTER 1 — THE HUNTER (center): Wears a felt trench coat and fedora like a film noir detective. Pinning a new index card to the corkboard with determination. Focused, intense, leaning in.

CHARACTER 2 — THE SKEPTIC (left): A developer in a black hoodie, arms crossed, leaning back slightly. Looking at the board with a doubtful, unconvinced expression. Head tilted, not buying it.

CHARACTER 3 — THE REFEREE (right): Wears a black and white vertically striped referee shirt with a silver whistle around their neck. Examining the board closely, one hand on chin, about to make a ruling on whether the evidence holds up.

The corkboard has index cards with code snippets, error messages, printed stack traces, all connected with red string in a conspiracy pattern. A small round fuzzy furry felt BUG creature — fluffy with big innocent googly eyes and tiny antennae — is tangled in the red string at the center of the board.

All puppets have felt/fleece skin, yarn hair in different bright colors, bead eyes, Muppet-style hinged mouths. Real fabric clothing at human scale.

Dark blue-noir atmosphere with the single warm lamp as key light on the left. The RIGHT SIDE and UPPER PORTION have darker negative space. Photorealistic office environment — real desk, coffee cups, papers, corded phone. Shallow depth of field. Wide 16:9 cinematic composition."""

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 evidence board with 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-board-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!")
