#!/usr/bin/env python3
"""Generiert ein großes Hero-Bild für die Weltküche-Lehrer-Übersicht.
Output: App/sims/weltkueche/assets/img/hero-card.webp (960x480)"""
import json, os, subprocess, sys, tempfile, base64
from pathlib import Path

KEY = None
env_path = 'C:/xampp/htdocs/geograsim/App/.env.local'
with open(env_path, 'r', encoding='utf-8') as f:
    for line in f:
        if line.startswith('OPENAI_API_KEY='):
            KEY = line.split('=', 1)[1].strip().strip('"').strip("'")
            break
if not KEY:
    sys.exit('OPENAI_API_KEY nicht in .env.local')

OUT_DIR  = Path('C:/xampp/htdocs/geograsim/App/sims/weltkueche/assets/img')
ORIG_DIR = OUT_DIR / '_original'
OUT_DIR.mkdir(parents=True, exist_ok=True)
ORIG_DIR.mkdir(parents=True, exist_ok=True)

PROMPT = (
    "CRITICAL STYLE: flat vector illustration, children's-book / Scandinavian poster art, "
    "NO photography, NO 3D rendering, NO realistic shading, NO photographic textures, NO gradients. "
    "Wide-shape silhouettes with flat solid color fills, clean cut edges, simple geometric forms. "
    "Strict palette: dark forest green #1f4b37, sage green #4a7c4e, yellow-mustard #e8c547, "
    "warm beige #e8e4d8, white highlights, optional small red-orange accent #c97b5a. "
    "ASPECT: wide horizontal banner (2:1) — composition fills the full width edge to edge, "
    "background warm beige #e8e4d8. "
    "COMPOSITION: a large stylized world map silhouette in sage green spans the center, "
    "with dotted dark forest green trade-route lines arcing from various continents toward Europe. "
    "Around the edges, floating flat food icons (each clearly recognizable from its silhouette): "
    "a yellow-mustard banana (top-left), a red-orange tomato (top-right), a forest-green coffee bean cluster (right), "
    "a sage-green chili pepper (bottom-right), a beige loaf of bread (bottom-left), a small white cheese wedge (left), "
    "a brown chocolate square (top-center). "
    "The trade-route lines connect each food icon to its origin region on the map. "
    "Small ship and airplane silhouettes in dark forest green along two of the routes. "
    "FORBIDDEN: text, letters, numbers, watermarks, logos, borders, frames, photo-realistic lighting, "
    "lens-flare, people faces, hands, brand names, shadows."
)

def generate():
    out_png  = ORIG_DIR / 'hero-card.png'
    out_webp = OUT_DIR / 'hero-card.webp'
    body = json.dumps({'model': 'gpt-image-2', 'prompt': PROMPT, 'n': 1, 'size': '1536x1024'}, ensure_ascii=False)
    with tempfile.NamedTemporaryFile(mode='w', encoding='utf-8', suffix='.json', delete=False) as f:
        f.write(body); bpath = f.name
    r = subprocess.run(['curl', '-sS',
        '-X', 'POST', 'https://api.openai.com/v1/images/generations',
        '-H', 'Authorization: Bearer ' + KEY,
        '-H', 'Content-Type: application/json',
        '--data-binary', '@' + bpath], capture_output=True, text=True, timeout=300)
    os.unlink(bpath)
    try:
        data = json.loads(r.stdout)
        item = data['data'][0]
        if 'b64_json' in item:
            with open(out_png, 'wb') as f:
                f.write(base64.b64decode(item['b64_json']))
        elif 'url' in item:
            subprocess.run(['curl', '-sS', '-o', str(out_png), item['url']],
                           capture_output=True, text=True, timeout=60)
        else:
            print(r.stdout[:500])
            return False
    except Exception as e:
        print(f'FAIL: {e}\n{r.stdout[:300]}')
        return False
    if not out_png.exists() or out_png.stat().st_size < 10000:
        return False
    try:
        from PIL import Image
        img = Image.open(out_png)
        # 2:1 ratio, 960x480 für Web-Hero
        w, h = img.size
        target_ratio = 2 / 1
        if w / h > target_ratio:
            new_w = int(h * target_ratio); off = (w - new_w) // 2
            img = img.crop((off, 0, off + new_w, h))
        else:
            new_h = int(w / target_ratio); off = (h - new_h) // 2
            img = img.crop((0, off, w, off + new_h))
        img = img.resize((960, 480), Image.LANCZOS)
        img.save(out_webp, 'webp', quality=88, method=6)
    except Exception as e:
        print(f'WebP-Fail: {e}')
        return False
    return True

print('-> hero-card ...', flush=True)
ok = generate()
print(f'   {"OK" if ok else "FAIL"}: hero-card.webp')
