#!/usr/bin/env python3
"""Generate logo proposals for Olevia & Aria using Recraft API."""
import os, json, requests, base64, time
from pathlib import Path

API_KEY = os.environ.get("RECRAFT_API_KEY")
BASE = "https://external.api.recraft.ai/v1"
HEADERS = {"Authorization": f"Bearer {API_KEY}"}
OUT = Path("/root/.openclaw/workspace/public/phat-foods/logos")
OUT.mkdir(parents=True, exist_ok=True)

def generate_logo(prompt, filename, style="digital_illustration"):
    """Generate a logo via Recraft."""
    print(f"  Generating {filename}...")
    body = {
        "prompt": prompt,
        "style": style,
        "model": "recraftv3",
        "size": "1024x1024"
    }
    try:
        r = requests.post(f"{BASE}/images/generations", headers=HEADERS, json=body, timeout=120)
        if r.status_code != 200:
            print(f"    ERROR {r.status_code}: {r.text[:200]}")
            return None
        data = r.json()
        # Recraft returns image URL
        if "data" in data and len(data["data"]) > 0:
            img_url = data["data"][0].get("url")
            if img_url:
                img_r = requests.get(img_url, timeout=60)
                if img_r.status_code == 200:
                    (OUT / filename).write_bytes(img_r.content)
                    print(f"    Saved {filename} ({len(img_r.content)} bytes)")
                    return filename
            # Try base64
            b64 = data["data"][0].get("b64_json")
            if b64:
                img_bytes = base64.b64decode(b64)
                (OUT / filename).write_bytes(img_bytes)
                print(f"    Saved {filename} ({len(img_bytes)} bytes)")
                return filename
        print(f"    No image in response: {json.dumps(data)[:200]}")
        return None
    except Exception as e:
        print(f"    Exception: {e}")
        return None

# Direction A: Liquid Gold Warmth (serif-based)
direction_a = [
    ("Create a premium wordmark logo for 'Olevia' — a luxury food ingredient brand. Modern serif typeface with high contrast strokes. Dark olive green (#2D4A22) on white background. Elegant, refined, like a premium olive oil label. Clean composition, no icons, just typography. Professional brand identity design.", "a-olevia-serif.png"),
    ("Create a premium wordmark logo for 'Aria' — a luxury food ingredient brand. Modern serif typeface with flowing elegant curves. Warm amber color (#D4A574) on white background. Sophisticated, like fine spirits branding. Clean composition, no icons, just the word. Professional brand identity design.", "a-aria-serif.png"),
]

# Direction B: Clean Authority (geometric sans)  
direction_b = [
    ("Create a clean modern wordmark logo for 'Olevia' — a premium food technology brand. Geometric sans-serif typeface, medium weight, generous letter spacing. Dark olive green (#2D4A22) on white background. Minimal, confident, like Perplexity or Oatly branding style. No icons, pure typography. Professional logo design.", "b-olevia-sans.png"),
    ("Create a clean modern wordmark logo for 'Aria' — a premium food technology brand. Geometric sans-serif typeface, medium weight, wide tracking. Dark olive green (#2D4A22) on white background. Category-defining confidence. No icons, pure typography. Professional logo design.", "b-aria-sans.png"),
]

# Direction C: Humanist Warmth (rounded sans)
direction_c = [
    ("Create a warm approachable wordmark logo for 'Olevia' — a natural food ingredient brand. Rounded sans-serif typeface with soft terminals, medium weight. Dark olive green (#2D4A22) on white background. Friendly but premium, like Headspace branding. No icons, just the word. Professional logo design.", "c-olevia-rounded.png"),
    ("Create a warm approachable wordmark logo for 'Aria' — a natural food ingredient brand. Rounded sans-serif typeface with gentle curves, medium weight. Dark olive green (#2D4A22) on white background. Approachable luxury. No icons, just the word. Professional logo design.", "c-aria-rounded.png"),
]

# Bonus: Logo marks (icon + type)
logo_marks = [
    ("Create a logo for 'Olevia' — a premium fat ingredient brand. Combine a minimal olive leaf icon with clean sans-serif wordmark. Dark olive green (#2D4A22) and warm amber (#D4A574). Simple, modern, scalable. White background. Professional brand identity.", "mark-olevia.png"),
    ("Create a logo for 'Aria' — a premium food ingredient brand. Combine a minimal abstract flowing air/wave icon with clean serif wordmark. Dark olive green (#2D4A22) and warm amber (#D4A574). Elegant, modern, scalable. White background. Professional brand identity.", "mark-aria.png"),
]

all_prompts = [
    ("Direction A — Liquid Gold Warmth", direction_a),
    ("Direction B — Clean Authority", direction_b),
    ("Direction C — Humanist Warmth", direction_c),
    ("Logo Marks", logo_marks),
]

results = {}
for dir_name, prompts in all_prompts:
    print(f"\n{dir_name}")
    for prompt, filename in prompts:
        result = generate_logo(prompt, filename)
        results[filename] = result
        time.sleep(2)  # Rate limit

# Summary
success = sum(1 for v in results.values() if v)
print(f"\n{'='*40}")
print(f"Generated {success}/{len(results)} logos")
print(f"Output: {OUT}")

with open(OUT / "results.json", "w") as f:
    json.dump(results, f, indent=2)
