#!/usr/bin/env python3
"""Generate strategy brief mockup variations using Gemini image generation."""

import base64
import os
import json
import urllib.request
import urllib.error

API_KEY = os.environ["GEMINI_API_KEY"]
OUTPUT_DIR = os.path.dirname(os.path.abspath(__file__))
MODEL = "gemini-2.5-flash-image"

prompts = [
    {
        "file": "strategy-brief-v1.png",
        "prompt": (
            "A high-fidelity product mockup photograph of an iPad Pro in landscape orientation, "
            "placed on a clean white marble desk surface, displaying a strategy brief document. "
            "Soft natural daylight from the left. Slight top-down angle (about 15 degrees). "
            "The iPad screen has a white background and shows: "
            "Top left: 'curious endeavor.' in red italic serif font as branding. "
            "Top right: 'Dove · DACH · March 2026' in small grey text. "
            "Below that, three large metric cards side by side: "
            "First card shows '+34%' in large green text with 'Sustainability Sentiment' below in small grey. "
            "Second card shows '2.4x' in large black text with 'Authenticity Engagement' below in small grey. "
            "Third card shows '-18%' in large red text with 'Competitor Share of Voice' below in small grey. "
            "Below the cards: 'STRATEGIC DIRECTION' as a red uppercase label. "
            "Below that, a large serif headline: 'Lead with your supply chain story in DACH. Price-value positioning in UK.' "
            "Professional Apple-style device photography. 16:9 aspect ratio. Photorealistic. Sharp focus on screen text. "
            "Minimal, premium aesthetic."
        ),
    },
    {
        "file": "strategy-brief-v2.png",
        "prompt": (
            "A high-fidelity product mockup photograph of an iPad Pro in landscape orientation, "
            "floating at a slight angle on a soft light grey gradient background. Studio lighting with "
            "subtle shadow beneath the device. Straight-on front view. "
            "The iPad screen has a clean white background and displays a strategy brief document: "
            "Top left: 'curious endeavor.' in red italic serif font as branding. "
            "Top right: 'Dove · DACH · March 2026' in small grey text. "
            "Three large stat cards in a row: "
            "'+34%' in bold green (label: Sustainability Sentiment), "
            "'2.4x' in bold black (label: Authenticity Engagement), "
            "'-18%' in bold red (label: Competitor Share of Voice). "
            "Red uppercase label: 'STRATEGIC DIRECTION'. "
            "Large serif headline below: 'Lead with your supply chain story in DACH. Price-value positioning in UK.' "
            "Professional Apple marketing style photography. 16:9 ratio. Crisp, readable text on screen. "
            "Premium tech product shot with clean studio background."
        ),
    },
    {
        "file": "strategy-brief-v3.png",
        "prompt": (
            "A high-fidelity product mockup photograph of an iPad Pro in landscape orientation, "
            "resting on a minimal concrete desk surface. Warm ambient studio lighting from above right, "
            "creating soft shadows. Three-quarter perspective view showing slight depth. "
            "The iPad screen displays a white strategy brief document: "
            "Top left corner: 'curious endeavor.' in red italic serif branding. "
            "Top right corner: 'Dove · DACH · March 2026' in grey. "
            "Three prominent metric cards arranged horizontally: "
            "'+34%' large green number with 'Sustainability Sentiment' caption, "
            "'2.4x' large black number with 'Authenticity Engagement' caption, "
            "'-18%' large red number with 'Competitor Share of Voice' caption. "
            "'STRATEGIC DIRECTION' in red uppercase tracking. "
            "Serif headline: 'Lead with your supply chain story in DACH. Price-value positioning in UK.' "
            "Professional Apple product photography aesthetic. 16:9 ratio. Warm-toned, editorial quality. "
            "Readable screen content. Shallow depth of field on background."
        ),
    },
]

def generate_image(prompt_text, output_path):
    """Call Gemini API to generate image."""
    url = f"https://generativelanguage.googleapis.com/v1beta/models/{MODEL}:generateContent?key={API_KEY}"
    
    payload = {
        "contents": [
            {
                "parts": [
                    {"text": prompt_text}
                ]
            }
        ],
        "generationConfig": {
            "responseModalities": ["IMAGE", "TEXT"]
        }
    }
    
    data = json.dumps(payload).encode("utf-8")
    req = urllib.request.Request(url, data=data, headers={"Content-Type": "application/json"})
    
    try:
        with urllib.request.urlopen(req, timeout=180) as resp:
            result = json.loads(resp.read())
    except urllib.error.HTTPError as e:
        body = e.read().decode()
        print(f"HTTP {e.code}: {body[:500]}")
        raise
    
    # 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_path, "wb") as f:
                    f.write(img_data)
                print(f"Saved: {output_path} ({len(img_data)} bytes)")
                return True
            elif "text" in part:
                print(f"Text: {part['text'][:200]}")
    
    print(f"No image in response: {json.dumps(result)[:500]}")
    return False


if __name__ == "__main__":
    for item in prompts:
        out = os.path.join(OUTPUT_DIR, item["file"])
        print(f"\n--- Generating {item['file']} ---")
        try:
            generate_image(item["prompt"], out)
        except Exception as e:
            print(f"Error generating {item['file']}: {e}")
