import os, json, base64, requests, time
from pathlib import Path

api_key = os.environ.get('GEMINI_API_KEY') or "AIzaSyDXqYZInk83iVV4mD29pSuHQKbgkiI1x9Q"
url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-image:generateContent?key={api_key}"
outdir = Path("/root/.openclaw/workspace/phat-deck-images/slide16/v2/")

def generate(prompt, filename):
    payload = {
        "contents": [{"parts": [{"text": prompt}]}],
        "generationConfig": {
            "responseModalities": ["IMAGE", "TEXT"],
            "temperature": 0.7
        }
    }
    resp = requests.post(url, json=payload, headers={"Content-Type": "application/json"}, timeout=120)
    result = resp.json()
    for cand in result.get("candidates", []):
        for part in cand.get("content", {}).get("parts", []):
            if "inlineData" in part:
                data = base64.b64decode(part["inlineData"]["data"])
                filepath = outdir / filename
                with open(filepath, "wb") as f:
                    f.write(data)
                print(f"✓ {filename} ({len(data)} bytes)")
                return True
    reason = "unknown"
    try:
        reason = json.dumps(result.get("candidates", [{}])[0].get("finishReason", result.get("error", "unknown")))
    except:
        reason = str(result)[:200]
    print(f"✗ {filename} failed: {reason}")
    return False

prompts = {
    "A1_kitchen_hands.png": "Warm golden-amber monochromatic photograph. 3:4 vertical portrait. Chef's hands working with rich golden clarified fat in a professional kitchen. Everything bathed in warm honey-amber light — golden hour side lighting from left. Shallow depth of field, background dissolves into warm bokeh. Stainless steel surfaces reflect amber-gold tones. The fat is luminous, catching light like liquid gold. Textural richness — you can feel the viscosity. Intimate, premium, quiet confidence. No text, no labels.",
    "A2_fat_pour.png": "Warm golden-amber monochromatic photograph. 3:4 vertical portrait. Liquid golden fat being poured in a professional kitchen — a thick, viscous stream of clarified butter-like substance catching warm directional light. Everything in the amber-honey-butterscotch color spectrum. Shallow depth of field with creamy warm bokeh background. Warm side lighting creates glow and highlights the liquid's texture. Premium, sensory, intimate. No text, no labels.",
    "A3_pastry_fold.png": "Warm golden-amber monochromatic photograph. 3:4 vertical portrait. Close-up of golden fat being folded into pastry dough on a warm-toned surface. Rich amber color grading throughout — like viewing through clarified butter. Warm directional golden light from upper left. Shallow depth of field. Textural detail in the fat and dough — you can feel the richness. Intimate, artisanal, premium quality. No cool tones. No text, no labels.",
    "A4_kitchen_scene.png": "Warm golden-amber monochromatic photograph. 3:4 vertical portrait. Professional kitchen scene — stainless steel surfaces reflecting warm amber light, golden fat preparations in bowls catching directional golden-hour light. Everything in warm honey-butterscotch-amber tones. Soft particles in the air catching light. Shallow depth of field. Warm, luminous, premium. The scene whispers quality and craft. No text, no labels.",
    "B1_fat_block_unwrapped.png": "Warm golden-amber monochromatic photograph. 3:4 vertical portrait. A premium plant-based fat block wrapped in elegant minimal packaging, partially unwrapped to reveal rich golden butter-like product. Everything bathed in warm amber-honey light — golden hour side lighting. The product glows with rich butterscotch tones. Shallow depth of field with warm creamy bokeh. On a warm-toned surface — wood or marble catching amber reflections. Textural richness in the fat's surface. Intimate, premium, artisanal. No brand text, no logos.",
    "B2_stacked_blocks.png": "Warm golden-amber monochromatic photograph. 3:4 vertical portrait. Stack of premium fat blocks in beautiful packaging — clean design with gold and cream tones. One block partially opened showing rich golden product. Everything in warm amber-honey color spectrum. Directional golden light from left creating shadows and glow. Shallow depth of field. Packaging suggests luxury through design language. Warm, intimate, quiet confidence. No text, no logos, no brand names.",
    "B3_sliced_block.png": "Warm golden-amber monochromatic photograph. 3:4 vertical portrait. Single premium fat block sliced to show cross-section — rich golden interior with smooth, dense texture like European-style butter. The cross-section catches warm amber-gold directional light, glowing from within. Elegant wrapper pulled back. Everything in warm honey-butterscotch-amber tones. Shallow depth of field. Textural richness — you can feel the density and creaminess. No text, no logos.",
    "B4_lifestyle_board.png": "Warm golden-amber monochromatic photograph. 3:4 vertical portrait. Premium fat block product in elegant packaging arranged on a warm wooden board with linen and a golden croissant. Everything in warm amber-honey monochrome — golden hour directional light flooding from left. Shallow depth of field dissolving background into warm creamy bokeh. The fat block and croissant glow with rich butterscotch tones. Intimate, sensory, premium lifestyle. No text, no logos, no brand names."
}

failed = []
for filename, prompt in prompts.items():
    print(f"\n--- Generating {filename} ---")
    ok = generate(prompt, filename)
    if not ok:
        failed.append((filename, prompt))
    time.sleep(2)  # rate limit buffer

# Retry failures once
if failed:
    print(f"\n=== Retrying {len(failed)} failed images ===")
    time.sleep(5)
    still_failed = []
    for filename, prompt in failed:
        print(f"\n--- Retry: {filename} ---")
        ok = generate(prompt, filename)
        if not ok:
            still_failed.append(filename)
        time.sleep(2)
    if still_failed:
        print(f"\n⚠ Still failed after retry: {still_failed}")

print("\n=== Final results ===")
for f in sorted(outdir.glob("*.png")):
    print(f"  {f.name}: {f.stat().st_size:,} bytes")
print("Done.")
