#!/usr/bin/env python3
"""Generate /bug-hunt promotional image using Gemini image generation."""

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

API_KEY = os.environ.get("GEMINI_API_KEY")
if not API_KEY:
    sys.exit("GEMINI_API_KEY not set")

# Read reference image
ref_path = "/root/.openclaw/media/inbound/62a606e4-4735-473e-b60e-3a216d48db42.png"
with open(ref_path, "rb") as f:
    ref_b64 = base64.b64encode(f.read()).decode()

prompt = """Create a cinematic promotional image in the EXACT same style as the reference image I'm providing. Same retro hacker aesthetic: dark room, green glow, CRT monitors, cables, vintage tech equipment.

KEY CHANGES from the reference:
1. The main CRT monitor displays "/bug-hunt" in large glowing green terminal text (instead of "/last30days")
2. There are 3 distinct silhouetted figures/characters visible in the scene, each representing a different "type" of bug hunter:
   - A hacker type at a desk with multiple screens
   - A detective type with a magnifying glass examining code
   - A soldier/tactical type with night vision goggles
3. Small glowing bug icons (like actual insects but digital/neon) scattered around the scene being "hunted"
4. Keep the same dark moody atmosphere, green color palette, and retro-futuristic feel
5. Same wide aspect ratio as the reference (roughly 16:9 / 1200x630)

The image should feel like a movie poster for a cyberpunk bug-hunting operation. Cinematic, atmospheric, professional quality."""

model = "gemini-3.1-flash-image-preview"
url = f"https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent?key={API_KEY}"

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("Generating image with Gemini...")
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)

# Extract image from response
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"])
            out = "/root/.openclaw/workspace/output/bug-hunt-promo.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)")
            sys.exit(0)

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