#!/usr/bin/env python3
"""Tranche C + D — 10 Europa + 5 exotisch = 15 Bilder.
Methodik V1 (Plattform-Palette) + Naturfarben-Hinweise."""
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

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

PROMPT_BASE = ("CRITICAL STYLE: flat vector illustration, children's-book / Scandinavian poster art, "
               "NO photography, NO 3D rendering, NO realistic shading, NO photographic textures, NO gradients. "
               "Style is 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, beige #e8e4d8, white highlights, optional small red-orange accent #c97b5a. "
               "WHEN the dish contains an EGG with visible yolk, the yolk MUST be bright yellow #f5c63a — never green or sage. "
               "Plate is round, dark forest-green rim, viewed top-down, filling about 75% of the square frame. "
               "Background is flat beige #e8e4d8. "
               "FORBIDDEN: text, letters, numbers, watermarks, logos, borders, frames, photo-realistic lighting, lens-flare, "
               "people faces with detail, brand names, NO green egg yolks.")

DISHES = {
    # === Tranche C — 10 Europa ===
    'pizza-margherita': "On the plate: a round pizza viewed top-down — dough rim slightly puffed in beige #e8e4d8, red-orange tomato sauce #c97b5a covering the inside, white-cream mozzarella blobs scattered, 3-4 small sage-green basil leaves on top, a thin spiral of golden olive-oil drizzle.",
    'spaghetti-carbonara': "On the plate: a swirling nest of beige-yellow #e8c547 spaghetti strands in the center, scattered with small brown #a87253 guanciale bacon bits, dark forest-green pepper flecks, a few white-cream cheese flecks.",
    'paella-valenciana': "On the plate (which is actually a wide shallow pan/paella dish in dark forest-green): saffron-yellow #e8c547 rice covering the whole surface, with chunks of brown-beige #a87253 chicken and rabbit pieces scattered, a few red-orange #c97b5a tomato bits, green flat bean strips, a few darker rice patches showing the 'socarrat' crust.",
    'tortilla-espanola': "On the plate: a thick round egg-potato omelette wedge, sliced — outer layer golden-yellow #e8c547, inside layered with thin beige potato slices visible. Top view, one slice taken out to reveal the layered texture. Sage-green parsley garnish.",
    'ratatouille': "On the plate: a colorful round arrangement of overlapping thin vegetable slices in concentric rings — alternating dark forest-green zucchini, sage-green eggplant, red-orange #c97b5a tomato, yellow-mustard #e8c547 yellow pepper slices, all sitting on a dark sauce. Top-down spiral view. A tiny sage-green herb sprig in center.",
    'quiche-lorraine': "On the plate: a wedge slice of a baked tart, top view — golden-yellow #e8c547 egg-cream filling baked smooth, with small brown #a87253 bacon bits scattered through it, a buttery beige pastry crust edge visible. Top crust shows slight golden browning patches.",
    'moussaka': "On the plate: a rectangular slice of layered casserole shown from the side — layers visible: dark forest-green eggplant, brown #a87253 lamb-tomato meat sauce, dark forest-green eggplant again, golden-yellow #e8c547 béchamel cheese topping with a slight crust. Side cut showing the strata.",
    'kanelbulle': "On the plate: 2 round spiral-shaped cinnamon buns viewed top-down, beige-golden #e8c547 spirals with darker brown #a87253 cinnamon-sugar filling visible in the spiral lines, sprinkled with white pearl sugar crystals on top.",
    'pierogi-ruskie': "On the plate: 5-6 half-moon dumplings arranged in a circle, beige pasta shells #e8e4d8, drizzled with golden-yellow #e8c547 melted butter and topped with crispy brown-beige #a87253 fried onion rings, sage-green chive flecks scattered.",
    'gulasch': "In a deep bowl with dark forest-green rim: thick stew with chunks of brown #a87253 beef, orange #d97a2c carrot rounds, beige potato cubes, red-orange #c97b5a paprika tones throughout the rich sauce. A sage-green parsley sprig garnish on top.",

    # === Tranche D — 5 exotisch ===
    'gemuese-curry': "On the plate: a generous mound of bright yellow-mustard #e8c547 turmeric curry stew with chunks of orange #d97a2c carrot, sage-green broccoli florets, beige potato cubes, red-orange #c97b5a chili flakes scattered, served alongside white-beige basmati rice on the side. Fresh sage-green coriander leaves on top.",
    'sushi-maki': "On the plate: 4-6 round sushi rolls arranged in a row, each showing the cross-section: a dark forest-green nori seaweed outer layer, white rice ring inside, in the center a tiny dark green avocado piece next to small orange carrot bits. A pile of pink pickled ginger on the side, a tiny mound of sage-green wasabi, a small dish of dark soy sauce.",
    'pad-thai': "On the plate: a tangle of beige flat rice noodles, scattered with chunks of golden-yellow #e8c547 scrambled egg, beige tofu cubes, light sage-green bean sprouts, frizzly green spring onion strips, red-orange #c97b5a chili flakes, and chunks of brown #a87253 peanuts. A bright yellow-green lime wedge on the side.",
    'falafel-hummus': "On the plate: 4 round brown-beige #a87253 fried falafel balls arranged around a central mound of creamy beige-yellow #e8c547 hummus that has a small well of golden olive oil in the center sprinkled with red-orange paprika dust. Sage-green parsley flecks all around, with a few beige flatbread triangles at the edge.",
    'guacamole-tortillas': "On the plate split into two: LEFT a deep dark forest-green ceramic bowl filled with chunky sage-green guacamole, with small red-orange #c97b5a tomato bits, white onion flecks, sage-green coriander leaves on top. RIGHT 3-4 thin round corn tortillas stacked, beige-yellow #e8c547 color with slight darker patches from grilling.",
}

def generate(dish_id, scene):
    out_png  = ORIG_DIR / f'{dish_id}.png'
    out_webp = OUT_DIR / f'{dish_id}.webp'
    if out_webp.exists():
        print(f'   SKIP (existiert): {out_webp.name}')
        return True
    prompt = PROMPT_BASE + "\n\nSCENE: " + scene
    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(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:
            return False
    except Exception as e:
        print(f'   FAIL: {r.stdout[:200] if r.stdout else e}')
        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).resize((512, 512), Image.LANCZOS)
        img.save(out_webp, 'webp', quality=85, method=6)
    except Exception as e:
        print(f'   WebP-Fail: {e}'); return False
    return True

ids = sys.argv[1:] if len(sys.argv) > 1 else list(DISHES.keys())
for d in ids:
    if d not in DISHES:
        print(f'-> {d}: UNBEKANNT'); continue
    print(f'-> {d} ...', flush=True)
    ok = generate(d, DISHES[d])
    print(f'   {"OK" if ok else "FAIL"}: {d}.webp')
