#!/usr/bin/env python3
"""Evidence board - hunter/skeptic/referee - 1:1 square for Twitter post."""

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 square 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 on 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.

CHARACTER 2 — THE SKEPTIC (left): Developer in a black hoodie, arms crossed, leaning back. Doubtful expression, head tilted, not buying it.

CHARACTER 3 — THE REFEREE (right): Black and white vertically striped referee shirt, silver whistle around neck. Examining the board closely, hand on chin, about to make a ruling.

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

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

Dark blue-noir atmosphere, warm lamp key light from left. Upper portion has dark negative space for text. Photorealistic office — real desk, coffee cups, papers. Shallow depth of field. SQUARE 1:1 composition optimized for social media."""

payload = {
    "instances": [{"prompt": prompt}],
    "parameters": {
        "sampleCount": 4,
        "aspectRatio": "1:1",
        "personGeneration": "allow_adult"
    }
}

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

print("Generating 1:1 evidence board...")
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-square-{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!")
