#!/usr/bin/env python3
"""Regeneriert nur die Sachertorte mit explizit dunkelbraunem Schoko-Charakter."""
import json, os, subprocess, 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'

# Spezialprompt: Schokolade muss DARK CHOCOLATE BROWN sein,
# NICHT in der Plattform-Palette (kein dark forest green!).
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. "
    "Style is wide-shape silhouettes with flat solid color fills, clean cut edges, simple geometric forms. "
    "Plate is round, dark forest-green #1f4b37 rim, viewed top-down or slightly tilted. "
    "Background is flat beige #e8e4d8. "
    "FORBIDDEN: text, letters, numbers, watermarks, logos, borders, frames, photo-realistic lighting.\n\n"
    "SCENE: a single wedge slice of Sachertorte on the plate, viewed slightly tilted to show the cross-section.\n"
    "CRITICAL FOOD COLORS: the chocolate glaze covering the top and outer sides of the slice MUST be DARK CHOCOLATE BROWN #3a1f12 — "
    "deep, glossy-looking but flat-shaped (no shine, no gradient). NOT green, NOT mustard, NOT olive — "
    "true dark brown like dark chocolate. The cake sponge inside is MEDIUM CHOCOLATE BROWN #6a3a20 — clearly cocoa-toned. "
    "ONE thin horizontal stripe of bright orange-amber apricot jam #d97a2c runs through the middle of the cake. "
    "Next to the cake slice, a small dollop of WHITE-CREAM #fafaf6 whipped cream as a flat shape. "
    "Optional: 3 tiny dark-chocolate shavings as small dark brown #3a1f12 curls on the white cream. "
    "Sachertorte must look unmistakably chocolatey — dark brown, decadent, festive. "
    "NO green color anywhere on the cake or chocolate."
)

def generate():
    out_png  = ORIG_DIR / 'sachertorte.png'
    out_webp = OUT_DIR / 'sachertorte.webp'
    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)
    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)
    from PIL import Image
    img = Image.open(out_png).resize((512, 512), Image.LANCZOS)
    img.save(out_webp, 'webp', quality=85, method=6)
    print(f'OK: {out_webp.name} ({out_webp.stat().st_size//1024}K)')

generate()
