#!/usr/bin/env python3
"""Generiert das Weltküche-Card-Bild NEU — mit mehr Action, mehr Gerichten, mehr Kochen.
Ersetzt App/assets/img/card-weltkueche.webp.
"""
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      = Path('C:/xampp/htdocs/geograsim/App/assets/img/card-weltkueche.webp')
ORIG_PNG = Path('C:/xampp/htdocs/geograsim/App/assets/img/_original/card-weltkueche-v2.png')

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, red-orange accent #c97b5a. "
    "ASPECT: square format. Background warm beige #e8e4d8. "
    "COMPOSITION: a cheerful global cooking scene with multiple dishes from around the world and lots of action. "
    "Center: a wooden kitchen counter or table viewed slightly from above, showing 6-8 different finished dishes from different continents — "
    "a round pizza margherita with red tomato and white mozzarella slices (Italy), "
    "a green sushi roll segment with seaweed band (Japan), "
    "a yellow paella pan with rice and red bell pepper (Spain), "
    "a brown apple strudel slice with white cream (Austria), "
    "a steaming bowl of pho with noodles (Vietnam), "
    "a colorful taco with greens (Mexico), "
    "a small bowl of Indian curry with naan bread, "
    "a green falafel platter with hummus (Middle East). "
    "Floating around the dishes: small flat ingredients — a yellow banana, red chili, brown coffee bean, white rice grains, green herbs, "
    "a tiny globe icon, a chef's hat, a wooden spoon, steam wisps rising from 2-3 of the bowls. "
    "Above the scene: 2-3 dotted curved lines suggesting trade routes connecting the dishes. "
    "Mood: warm, lively, inviting — like an illustrated cookbook poster celebrating world cuisine. "
    "FORBIDDEN: text, letters, numbers, watermarks, logos, borders, frames, photo-realistic lighting, "
    "lens-flare, people faces, hands, brand names, shadows, plates with text on them."
)

def run():
    print('-> generating card-weltkueche v2 (action + 8 dishes)…', flush=True)
    body = json.dumps({'model': 'gpt-image-2', 'prompt': PROMPT, 'n': 1, 'size': '1024x1024'}, 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(ORIG_PNG, 'wb') as f:
                f.write(base64.b64decode(item['b64_json']))
        elif 'url' in item:
            subprocess.run(['curl', '-sS', '-o', str(ORIG_PNG), item['url']],
                           capture_output=True, text=True, timeout=60)
        else:
            print('FAIL:', r.stdout[:300]); return False
    except Exception as e:
        print(f'FAIL: {e}\n{r.stdout[:300]}'); return False
    if not ORIG_PNG.exists() or ORIG_PNG.stat().st_size < 10000:
        return False
    try:
        from PIL import Image
        img = Image.open(ORIG_PNG)
        img = img.resize((640, 640), Image.LANCZOS)
        img.save(OUT, 'webp', quality=88, method=6)
        print(f'OK: {OUT.name} ({OUT.stat().st_size} bytes)')
        return True
    except Exception as e:
        print(f'WebP-Fail: {e}'); return False

run()
