#!/usr/bin/env python3
"""The Catch 1:1 using reference image for character consistency."""

import base64
import json
import os
import sys
import urllib.request

API_KEY = os.environ.get("GEMINI_API_KEY")

# Use Gemini 3 Pro which can take reference images
model = "gemini-3-pro-image-preview"
url = f"https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent?key={API_KEY}"

# Load reference image
with open("/root/.openclaw/media/inbound/d8feaa06-bee6-4d45-ac89-6533aef0d574.png", "rb") as f:
    ref_b64 = base64.b64encode(f.read()).decode()

prompt = """Generate a NEW square 1:1 image using EXACTLY these same three puppet characters from the reference image, in the same art style:

1. LEFT — THE SKEPTIC: Orange messy yarn hair, black hoodie with white drawstrings, arms crossed, frowning/suspicious expression, round orange nose, big round white eyes with black pupils
2. CENTER — THE HUNTER: Brown fedora hat, camel/beige belted trench coat, brown yarn hair, holding up a glass mason jar containing a small fuzzy grey-green caterpillar bug with big googly eyes. Proud satisfied expression, orange nose
3. RIGHT — THE REFEREE: Black baseball cap, black-and-white vertically striped referee jersey, silver whistle on lanyard, one arm raised making an official call, red/orange nose

NEW SCENE — same characters but in a square 1:1 composition:
- The scene should show all three characters at roughly waist-up or chest-up
- Modern startup office background with monitors, sticky notes, plants, golden afternoon light
- The jar with the fuzzy bug should be prominently visible in the center
- The skeptic is leaning in to examine the jar closely, still doubtful
- The referee is pointing at the jar decisively, confirming the catch
- Same warm cinematic lighting, shallow depth of field
- Same Muppet felt/fleece texture quality — visible fabric grain on their skin
- NO TEXT on the image"""

payload = {
    "contents": [{
        "parts": [
            {"text": prompt},
            {"inline_data": {"mime_type": "image/png", "data": ref_b64}}
        ]
    }],
    "generationConfig": {
        "responseModalities": ["IMAGE", "TEXT"]
    }
}

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

print(f"Generating with {model} (reference image)...")
try:
    with urllib.request.urlopen(req, timeout=180) 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)

count = 0
for candidate in result.get("candidates", []):
    for part in candidate.get("content", {}).get("parts", []):
        if "inlineData" in part:
            img_data = base64.b64decode(part["inlineData"]["data"])
            count += 1
            out = f"/root/.openclaw/workspace/output/bug-hunt-tw-catch-ref-{count}.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 "text" in part:
            print(f"Text: {part['text'][:200]}")

if count == 0:
    print("No image in response")
    print(json.dumps(result, indent=2)[:500])
    sys.exit(1)
