#!/usr/bin/env python3
"""Generate 8 images for PHAT Foods Slide 16 (Growth Plan)."""

import os, sys, json, base64, time, requests
from pathlib import Path

OUTPUT_DIR = Path("/root/.openclaw/workspace/phat-deck-images/slide16")
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)

api_key = os.environ.get('GEMINI_API_KEY')
if not api_key:
    print("ERROR: GEMINI_API_KEY not set"); sys.exit(1)

MODEL = "gemini-2.5-flash-image"
URL = f"https://generativelanguage.googleapis.com/v1beta/models/{MODEL}:generateContent?key={api_key}"

PROMPTS = {
    "A1_chef_hands_golden_fat.png": "Bright high-key editorial food photography. 3:4 vertical portrait. A chef's hands working with golden, creamy fat in a professional stainless steel kitchen. The fat has a rich butter-gold color, smooth and luxurious texture. Cream and champagne color palette throughout. Stainless steel surfaces reflect warm champagne-gold light. Soft diffused directional lighting from upper left. Shallow depth of field. Premium culinary context. No text, no labels.",
    "A2_pouring_liquid_gold.png": "Bright high-key editorial food photography. 3:4 vertical portrait. Close-up of golden plant-based fat being poured or drizzled in a professional kitchen setting. Liquid gold stream catching the light. Background shows blurred stainless steel kitchen equipment. Cream, champagne, and pale gold tones. Bright throughout, no dark shadows. Soft diffused lighting. No text, no labels, no signage.",
    "A3_pastry_preparation.png": "Bright high-key editorial food photography. 3:4 vertical portrait. Professional pastry preparation with golden cream fat — a chef spreading or folding rich golden butter-like substance into dough or pastry on a marble countertop. Warm champagne-gold color palette. Kitchen setting, premium culinary quality. Shallow depth of field. No text, no labels.",
    "A4_kitchen_workspace.png": "Bright high-key editorial food photography. 3:4 vertical portrait. Wide shot of a premium commercial kitchen workspace with golden fat preparations. Multiple stainless steel bowls containing rich golden cream. Clean, organized, professional. Cream and champagne tones with natural bright light flooding from windows. No text, no labels.",
    "B1_single_block_unwrapped.png": "Bright high-key editorial product photography. 3:4 vertical portrait. A premium plant-based fat block wrapped in elegant minimal packaging — clean white and gold foil wrapper, partially unwrapped to reveal the golden butter-like product inside. Sitting on a light marble surface. Cream and champagne color palette. Studio lighting, soft shadows. Product looks premium, artisanal, high-end. No brand text, no logos — suggest premium through design language only.",
    "B2_stacked_blocks.png": "Bright high-key editorial product photography. 3:4 vertical portrait. Stack of three premium fat blocks in beautiful packaging — clean geometric design, gold and cream colors, foil-stamped wrapper. One block partially opened showing rich golden product. Light cream background. Soft directional lighting creating gentle shadows. Premium retail-ready aesthetic. No text, no logos, no brand names.",
    "B3_sliced_cross_section.png": "Bright high-key editorial product photography. 3:4 vertical portrait. Single premium fat block sliced to show cross-section — rich golden interior with smooth, dense texture like European-style butter. Elegant minimal wrapper pulled back. Small fresh herbs scattered nearby for scale and culinary context. Cream marble surface, champagne-gold tones. No text, no logos.",
    "B4_kitchen_vignette.png": "Bright high-key editorial product photography. 3:4 vertical portrait. Premium fat block product arranged in a styled kitchen vignette — the product in its elegant packaging alongside a wooden cutting board, linen napkin, and a warm croissant. Natural bright daylight. The packaging suggests luxury and quality through clean lines and gold accents. Cream and warm white color palette. No text, no logos, no brand names.",
}

def generate(prompt, filepath, attempt=1):
    payload = {
        "contents": [{"parts": [{"text": f"Generate an image: {prompt}"}]}],
        "generationConfig": {
            "temperature": 0.7,
            "responseModalities": ["IMAGE", "TEXT"]
        }
    }
    try:
        r = requests.post(URL, headers={"Content-Type": "application/json"}, json=payload, timeout=120)
        r.raise_for_status()
        result = r.json()
        if 'candidates' in result and result['candidates']:
            for part in result['candidates'][0].get('content', {}).get('parts', []):
                if 'inlineData' in part:
                    filepath.write_bytes(base64.b64decode(part['inlineData']['data']))
                    return True
        print(f"  No image in response: {json.dumps(result)[:300]}")
        return False
    except Exception as e:
        print(f"  Error (attempt {attempt}): {e}")
        return False

results = {}
for fname, prompt in PROMPTS.items():
    fp = OUTPUT_DIR / fname
    print(f"Generating {fname}...", flush=True)
    ok = generate(prompt, fp)
    if not ok:
        print(f"  Retrying {fname}...", flush=True)
        time.sleep(5)
        ok = generate(prompt, fp, attempt=2)
    results[fname] = ok
    size = fp.stat().st_size if ok and fp.exists() else 0
    print(f"  {'✓' if ok else '✗'} {fname} ({size:,} bytes)", flush=True)
    if ok:
        time.sleep(3)

print(f"\n{'='*50}")
successes = sum(1 for v in results.values() if v)
print(f"Generated {successes}/8 images")
for fname, ok in results.items():
    fp = OUTPUT_DIR / fname
    size = fp.stat().st_size if fp.exists() else 0
    print(f"  {'✓' if ok else '✗'} {fname} — {size:,} bytes")
