#!/usr/bin/env python3
"""Tranche B — 10 DACH-Gerichte. Methodik V1 (Plattform-Palette), aber bei
Eiern und kritischen Naturfarben explizite Farbangaben (Lehre aus V1-Gröstl-grün-Ei).
"""
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)

# V1-Prompt (Plattform-Palette) — aber mit expliziten Naturfarben-Hinweisen
# für kritische Lebensmittel-Komponenten wo nötig
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 = {
    'wiener-schnitzel': "On the plate: a large oval beige-mustard #e8c547 breaded cutlet (Wiener Schnitzel), the breading shown as a slightly textured flat shape with rippling edges. Next to it: a yellow lemon wedge as a flat triangular shape with yellow-mustard #e8c547 fill, a small sprig of sage-green parsley.",
    'sachertorte': "On the plate: a single round slice of a dark chocolate cake (Sachertorte), viewed top-down or slightly tilted — the slice shape is a wedge with dark forest-green chocolate glaze on top and outside, beige sponge inside, one thin orange-mustard #e8c547 stripe of apricot jam in the middle as a horizontal line. Beside: a small white-beige dollop of whipped cream.",
    'apfelstrudel': "On the plate: a thick diagonal slice of apple strudel, beige rolled pastry shape with thin spiral lines indicating the rolled dough, golden-mustard #e8c547 apple filling visible at the cut end. Light beige powdered sugar dust on top. A small sprig of sage-green mint as garnish.",
    'topfengolatschen': "On the plate: 2 square pastry pockets (Topfengolatschen) — beige #e8e4d8 golden pastry with 4 corners folded into the center showing white creamy filling in the middle. Light dust of powdered sugar on top (as small white dots).",
    'bayerische-brezel': "On the plate: a large brown-mahogany Bavarian pretzel (Brezel) as a flat 3-loop knot shape filling most of the plate, dark brown-beige #a87253 color with a sprinkle of large white salt crystals on top. Next to it: a small beige bowl with white-cream Obatzda cheese spread, topped with sage-green chive flecks and red-orange paprika sprinkle.",
    'schwaebische-maultaschen': "In the bowl: 3-4 large square dumplings (Maultaschen) — beige pasta squares filled visible — placed in a clear golden #e8c547 broth. The dumpling tops show a sage-green spinach hint through the dough. A few golden roasted onion strips beige-brown on top.",
    'rheinischer-sauerbraten': "On the plate: a stack of 3-4 thin slices of dark brown #a87253 braised beef (Sauerbraten), glazed with shiny dark sauce. Around: a small dollop of beige potato dumpling (Klöße), a few dark purple-red braised red cabbage strips (use forest-green and yellow-mustard mix for cabbage tone), 3 dark raisins as small dots in the sauce.",
    'schwarzwaelder-kirschtorte': "On the plate: a single wedge slice of a layered cake (Schwarzwälder Kirschtorte). Three layers visible from the side: dark forest-green chocolate sponge alternating with white whipped cream, red cherries (use red-orange #c97b5a) scattered in the middle layer. On top: a thick swirl of white cream with a single red cherry crown. Dark chocolate shavings as forest-green small slivers around.",
    'schweizer-kaesefondue': "Top-down view of a round shallow caquelon (fondue pot) in dark forest-green ceramic. Inside: smooth creamy golden-beige #e8c547 melted cheese filling the whole bowl, with two fondue forks sticking out at angles — fork handles dark forest-green. Beside the pot on the table: a small pile of beige bread cubes (4-5 cubes shown as flat square shapes).",
    'zuercher-geschnetzeltes': "On the plate, split visually in two: LEFT side a round golden-brown #e8c547 rösti (potato pancake) as a flat disc, very lightly textured. RIGHT side: a small mound of thin brown-beige #a87253 meat strips in cream sauce, with a few sage-green parsley flecks and dark grey-brown mushroom slices visible."
}

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')
