#!/usr/bin/env python3
"""Generate /bug-hunt in puppet world style - Recraft API."""

import json
import os
import sys
import urllib.request

API_KEY = "ONdPVa7auZzwGDtGvyJlgQxAzJ51RVkhQMeTQfTtuWBvfTqKOA7jibaMgHmtS6d0"

prompt = """A cinematic photograph of three handmade felt puppet characters in a modern office, hunting for software bugs. Muppet-style puppets with fleece/felt skin, yarn hair, bead eyes, hinged mouths.

Three puppet characters:
1. A nerdy puppet with glasses and hoodie, peering at a laptop with a magnifying glass
2. A punk puppet with colorful yarn hair and denim jacket, holding a butterfly net catching glowing digital bugs
3. A detective puppet in a felt trench coat and fedora, examining a corkboard with code printouts and red string

Small cute glowing neon bug insects float around. "/bug-hunt" text visible on a monitor screen in terminal font. 

Real photorealistic office environment, warm natural lighting, shallow depth of field. Fuzzy felt texture, visible seams, handmade quality. Warm earth tones with pops of color."""

url = "https://external.api.recraft.ai/v1/images/generations"

payload = {
    "prompt": prompt,
    "model": "recraftv3",
    "size": "1820x1024",
    "style": "realistic_image"
}

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

print("Generating with Recraft v3...")
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)

# Recraft returns URLs, download them
for i, img in enumerate(result.get("data", [])):
    img_url = img.get("url")
    if img_url:
        out = f"/root/.openclaw/workspace/output/bug-hunt-puppet-recraft-{i+1}.png"
        os.makedirs(os.path.dirname(out), exist_ok=True)
        dl_req = urllib.request.Request(img_url, headers={"User-Agent": "Mozilla/5.0"})
        with urllib.request.urlopen(dl_req, timeout=30) as r:
            with open(out, "wb") as f:
                f.write(r.read())
        sz = os.path.getsize(out)
        print(f"Saved: {out} ({sz} bytes)")

if not result.get("data"):
    print("No images in response")
    print(json.dumps(result, indent=2)[:500])
    sys.exit(1)
