#!/usr/bin/env python3
"""Generate typography logo concepts via Gemini image generation."""
import os, json, base64, requests, sys
from pathlib import Path

API_KEY = os.environ.get("GEMINI_API_KEY")
MODEL = "gemini-2.0-flash-exp"  # image generation capable model
OUT = Path("/root/.openclaw/workspace/phat-foods/logos")
OUT.mkdir(parents=True, exist_ok=True)

ENDPOINT = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash-exp:generateContent?key={API_KEY}"

PROMPTS = {
    "olevia_serif": (
        'Create a professional typography wordmark logo on a pure white background. '
        'The word "Olevia" in an elegant modern serif typeface. Dark olive green color (#2D4A22). '
        'Clean refined letterforms with generous spacing. Subtle olive branch detail integrated '
        'into the letter V. Minimalist premium food brand feel. Centered composition. No other text or elements.'
    ),
    "olevia_script": (
        'Create a professional typography wordmark logo on a pure white background. '
        'The word "Olevia" in a flowing elegant calligraphic script. Olive green ink color (#3A5F2C). '
        'Connected letterforms with graceful swashes. Organic and natural premium feel. '
        'Centered composition. No other text or elements.'
    ),
    "olevia_geometric": (
        'Create a professional typography wordmark logo on a pure white background. '
        'The word "OLEVIA" in clean geometric sans-serif uppercase letters. Dark olive green (#2D4A22). '
        'Precise proportions with modern minimalist aesthetic. Subtle leaf motif in negative space. '
        'Centered composition. No other text or elements.'
    ),
    "aria_serif": (
        'Create a professional typography wordmark logo on a pure white background. '
        'The word "Aria" in an elegant modern serif typeface. Dark olive green color (#2D4A22). '
        'Clean refined letterforms. The letter A has a subtle wind/breeze motif. '
        'Sophisticated minimalist premium food branding. Centered composition. No other text or elements.'
    ),
    "aria_script": (
        'Create a professional typography wordmark logo on a pure white background. '
        'The word "Aria" in a graceful flowing calligraphic script. Olive green color (#3A5F2C). '
        'Airy light strokes with elegant movement. Premium organic feel. '
        'Centered composition. No other text or elements.'
    ),
    "aria_geometric": (
        'Create a professional typography wordmark logo on a pure white background. '
        'The word "ARIA" in clean geometric sans-serif uppercase letters. Dark olive green (#2D4A22). '
        'Architectural precision. Subtle leaf incorporated into the A letterform. '
        'Modern minimal design. Centered composition. No other text or elements.'
    ),
}

def generate(name, prompt):
    print(f"Generating {name}...")
    body = {
        "contents": [{
            "parts": [{"text": prompt}]
        }],
        "generationConfig": {
            "responseModalities": ["TEXT", "IMAGE"],
        }
    }
    
    r = requests.post(ENDPOINT, json=body, timeout=120)
    if r.status_code != 200:
        print(f"  ERROR {r.status_code}: {r.text[:300]}")
        return None
    
    data = r.json()
    # Extract image from response
    candidates = data.get("candidates", [])
    for cand in candidates:
        parts = cand.get("content", {}).get("parts", [])
        for part in parts:
            if "inlineData" in part:
                img_data = part["inlineData"]
                mime = img_data.get("mimeType", "image/png")
                ext = "png" if "png" in mime else "jpg"
                b64 = img_data["data"]
                img_bytes = base64.b64decode(b64)
                fname = f"{name}.{ext}"
                (OUT / fname).write_bytes(img_bytes)
                print(f"  Saved {fname} ({len(img_bytes)} bytes)")
                return str(OUT / fname)
    
    print(f"  No image in response")
    # Debug: show what we got
    print(f"  Response keys: {list(data.keys())}")
    if candidates:
        parts = candidates[0].get("content", {}).get("parts", [])
        for p in parts:
            if "text" in p:
                print(f"  Text: {p['text'][:200]}")
    return None

if __name__ == "__main__":
    results = {}
    for name, prompt in PROMPTS.items():
        path = generate(name, prompt)
        results[name] = path
        
    with open(OUT / "results_gemini.json", "w") as f:
        json.dump(results, f, indent=2)
    
    success = sum(1 for v in results.values() if v)
    print(f"\nDone! {success}/{len(results)} logos generated in {OUT}")
