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

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

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

# Try imagen-4.0-fast (no reference image, just text prompt)
model = "imagen-4.0-generate-001"
url = f"https://generativelanguage.googleapis.com/v1beta/models/{model}:predict?key={API_KEY}"

prompt = """Cinematic wide-angle photograph of a dark retro hacker room. A large vintage CRT monitor in the center displays the text "/bug-hunt" in large bright green glowing terminal font. The room is filled with old computers, tangled cables, circuit boards, and vintage tech equipment. Green matrix-style code rains down on secondary monitors. Three distinct silhouetted figures are in the scene: a hacker at a desk, a detective with magnifying glass, and a tactical operative with night-vision goggles. Small glowing digital bug icons (like neon insects) float around the scene. Dark moody atmosphere with green color palette. Photorealistic, cinematic lighting, 16:9 aspect ratio."""

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

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=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
for pred in result.get("predictions", []):
    if "bytesBase64Encoded" in pred:
        img_data = base64.b64decode(pred["bytesBase64Encoded"])
        out = "/root/.openclaw/workspace/output/bug-hunt-promo-v2.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)
