#!/usr/bin/env python3
"""Generate photorealistic device mockup using Gemini image generation."""

import json
import base64
import sys
import urllib.request
import urllib.error

API_KEY = "AIzaSyDXqYZInk83iVV4mD29pSuHQKbgkiI1x9Q"
MODEL = "gemini-2.5-flash-image"
OUTPUT = "/root/.openclaw/workspace/work/pitches/brandwatch/visuals/mockup-test-1.png"

PROMPT = """Generate a photorealistic lifestyle mockup photograph. The scene shows a person's hands holding a MacBook Pro laptop, shot from above at a slight angle. The person is sitting on a concrete bench in natural daylight with soft shadows. The laptop screen displays a clean, modern social media analytics dashboard with dark UI — showing engagement metrics, line charts, and audience demographics. The image should look like high-end editorial product photography, similar to Mockup.Maison style — warm natural tones, shallow depth of field on the background, crisp focus on the device. The laptop screen should be clearly visible and readable. No watermarks or text overlays."""

url = f"https://generativelanguage.googleapis.com/v1beta/models/{MODEL}:generateContent?key={API_KEY}"

payload = {
    "contents": [{
        "parts": [{"text": PROMPT}]
    }],
    "generationConfig": {
        "responseModalities": ["TEXT", "IMAGE"]
    }
}

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

print("Generating image...")
try:
    with urllib.request.urlopen(req, timeout=120) as resp:
        result = json.loads(resp.read().decode("utf-8"))
except urllib.error.HTTPError as e:
    body = e.read().decode("utf-8")
    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"])
            with open(OUTPUT, "wb") as f:
                f.write(img_data)
            print(f"MEDIA: {OUTPUT}")
            print(f"Saved {len(img_data)} bytes")
            sys.exit(0)
        elif "text" in part:
            print(f"Text response: {part['text'][:200]}")

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