#!/usr/bin/env python3
"""Generate /bug-hunt using Gemini 3 pro image (can use reference)."""

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

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

# Read small reference
with open("/tmp/ref-small.jpg", "rb") as f:
    ref_b64 = base64.b64encode(f.read()).decode()

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

prompt = """Generate a new image inspired by this reference image's style and aesthetic. Keep the EXACT same dark retro hacker room atmosphere, green CRT glow, vintage computers, and tangled cables.

Changes:
1. The main CRT monitor text should say "/bug-hunt" (NOT "/last30days") in big green glowing terminal font
2. Add 3 silhouetted character types in the scene: a hacker at a desk, a detective with a magnifying glass, and a tactical operative with night-vision goggles
3. Add small glowing neon bug/insect icons floating around the scene
4. Keep the same wide cinematic aspect ratio
5. Same photorealistic quality and moody green color palette"""

payload = {
    "contents": [{
        "parts": [
            {"text": prompt},
            {"inline_data": {"mime_type": "image/jpeg", "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}...")
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)

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-v3.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)
        if "text" in part:
            print(f"Text: {part['text'][:200]}")

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