#!/usr/bin/env python3
"""Composite production assets screen into a Mockup.Maison-style device mockup."""

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/production-assets-mockup.png"

SCREEN_IMG = "/root/.openclaw/workspace/work/pitches/brandwatch/visuals/production-assets-screen.png"
REFERENCE_IMG = "/root/.openclaw/media/inbound/50838091-0cbe-4fa3-ae46-1d359742133f.jpg"

PROMPT = """Create a photorealistic device mockup photograph inspired by the reference image style (Mockup.Maison low-light MacBook Pro). 

The scene should show: A MacBook Pro on a dark surface, with a hand casually resting near the trackpad. Dramatic low-light photography with warm, soft ambient lighting from the side. The laptop screen is bright and clearly displays the production assets dashboard from the provided screenshot — preserve the white background UI with the Dove-branded creative assets grid layout exactly as shown. The screen should be the main light source, casting a subtle warm glow on the desk surface.

Style: editorial product photography, moody low-light, high contrast between the bright white screen and dark environment. Clean, minimal, premium feel. Slightly different angle from a standard straight-on shot — maybe a slight 15-degree offset.

IMPORTANT: The laptop screen must clearly display the dashboard content from the input screenshot. Keep the screen content sharp and readable."""

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

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

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

payload = {
    "contents": [{
        "parts": [
            {"text": PROMPT},
            {"inlineData": {"mimeType": screen_mime, "data": screen_b64}},
            {"inlineData": {"mimeType": ref_mime, "data": ref_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("Compositing into 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])
