#!/usr/bin/env python3
"""Generate a new Strategy Brief mockup inspired by the reference but with different device, gradient, setup."""

import json
import base64
import sys
import urllib.request
import urllib.error
from pathlib import Path

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

# The original reference (iPad on pink) and the CE-styled screen we want on the device
REFERENCE_IMG = "/root/.openclaw/media/inbound/90698dce-761f-4417-b6af-e06355965f87.png"
# We'll use the existing strategy brief screen from the brandwatch page
SCREEN_IMG = "/root/.openclaw/media/inbound/e092db37-ca96-428e-a137-ef5f069cfdb8.png"

PROMPT = """Create a photorealistic device mockup photograph. This should be INSPIRED BY the reference image style but with these key differences:

CHANGES FROM REFERENCE:
- DEVICE: Use a MacBook Pro laptop (NOT an iPad) — screen open, showing the strategy brief content from the second input image
- GRADIENT: Use a warm amber-to-deep-burgundy gradient background instead of pink — rich, premium feel
- SETUP: The laptop sits on a matte dark surface. A person's hand is gently touching the trackpad from the right side. There's a small ceramic coffee cup in the background left, slightly out of focus.
- ANGLE: Shot from above at roughly 30 degrees, slightly off-center to the left

KEEP FROM REFERENCE:
- The same Mockup.Maison editorial photography quality
- Soft, diffused lighting with no harsh shadows
- Clean, minimal composition
- The screen as the focal point with sharp content
- Premium, magazine-quality feel

The laptop screen must clearly display a strategy document with clean white background, showing positioning strategy content with headlines, bullet points, and data callouts. Keep the screen content sharp and readable.

OUTPUT: Photorealistic product photography, 16:9 aspect ratio."""

def load_image(path):
    data = Path(path).read_bytes()
    mime = "image/png" if path.endswith(".png") else "image/jpeg"
    return base64.b64encode(data).decode("utf-8"), mime

ref_b64, ref_mime = load_image(REFERENCE_IMG)
screen_b64, screen_mime = load_image(SCREEN_IMG)

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

payload = {
    "contents": [{
        "parts": [
            {"text": PROMPT},
            {"inlineData": {"mimeType": ref_mime, "data": ref_b64}},
            {"inlineData": {"mimeType": screen_mime, "data": screen_b64}}
        ]
    }],
    "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 strategy brief mockup...")
try:
    with urllib.request.urlopen(req, timeout=180) 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)

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"Saved: {OUTPUT} ({len(img_data)} bytes)")
            sys.exit(0)
        elif "text" in part:
            print(f"Text: {part['text'][:300]}")

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