#!/usr/bin/env python3
"""Generate logo proposals using style references from Assaf's taste board picks."""
import os, json, requests, base64, time
from pathlib import Path

API_KEY = os.environ["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 upload_style_ref(image_path):
    """Upload a style reference image and return the reference token."""
    with open(image_path, "rb") as f:
        r = requests.post(f"{BASE}/images/upload", 
                         headers=HEADERS,
                         files={"file": (os.path.basename(image_path), f, "image/png")},
                         timeout=60)
    if r.status_code == 200:
        data = r.json()
        return data.get("id") or data.get("image_id")
    print(f"  Upload failed: {r.status_code} {r.text[:200]}")
    return None

def generate(prompt, filename, style="realistic_image"):
    """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[:300]}")
            return None
        data = r.json()
        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"    OK ({len(img_r.content)} bytes)")
                    return filename
        print(f"    No image: {json.dumps(data)[:200]}")
        return None
    except Exception as e:
        print(f"    Exception: {e}")
        return None

# DIRECTION A: Warm Serif (Sometimes Always + Knitted City + Daily Form DNA)
# Characterful serif, warm cream backgrounds, earthy palette, gold/olive
a_prompts = [
    ("Premium wordmark logo 'Olevia' on warm cream background (#F5E6C8). Elegant modern serif typeface with high contrast strokes, similar to Canela or Freight Display. Dark olive green color (#2D4A22). Large scale, centered. Refined luxury food ingredient branding like premium olive oil. No icons, pure typography. Professional brand identity design.", "v2-a-olevia.png"),
    ("Premium wordmark logo 'Aria' on warm cream background (#F5E6C8). Elegant thin serif typeface with delicate curves, light weight. Warm amber gold color (#D4A574). Large scale, centered. Sophisticated food brand like artisanal spirits. No icons, pure typography. Professional brand identity.", "v2-a-aria.png"),
]

# DIRECTION B: Script/Brush (Sometimes Always + Good Thanks DNA)
# Hand-lettered feel, organic, warm, connected script
b_prompts = [
    ("Handwritten script wordmark logo 'Olevia' on white background. Flowing connected brush calligraphy, medium weight, natural imperfections. Dark olive green ink (#2D4A22). Warm, organic, artisanal food brand feel. Like premium hand-lettered packaging. Centered composition. Professional brand identity.", "v2-b-olevia.png"),
    ("Handwritten script wordmark logo 'Aria' on white background. Light airy connected script calligraphy, thin strokes with elegant flourishes. Warm amber color (#D4A574). Breezy, natural movement. Premium organic food brand. Centered composition. Professional brand identity.", "v2-b-aria.png"),
]

# DIRECTION C: Bold Condensed (Infatuation + FOLKS DNA)
# Heavy weight, condensed, confident, editorial
c_prompts = [
    ("Bold condensed wordmark logo 'OLEVIA' in all caps on white background. Heavy weight condensed sans-serif typeface, tight letter spacing. Dark olive green (#2D4A22). Industrial confidence, editorial poster aesthetic. Premium food brand with authority. No icons. Professional brand identity.", "v2-c-olevia.png"),
    ("Bold condensed wordmark logo 'ARIA' in all caps on white background. Heavy weight condensed sans-serif, tight tracking. Dark olive green (#2D4A22). Strong, confident, minimal. Food technology brand with editorial presence. No icons. Professional brand identity.", "v2-c-aria.png"),
]

# DIRECTION D: Rounded Serif (Knitted City / Caraway DNA)
# Warm rounded serif, golden tones, friendly premium
d_prompts = [
    ("Rounded serif wordmark logo 'Olevia' on warm cream background (#EDDDD0). Soft rounded serif typeface like Cooper Black or similar with bulbous terminals. Warm marigold gold color (#D4A017). Friendly, premium, craft food brand. Approachable luxury. No icons. Professional brand identity.", "v2-d-olevia.png"),
    ("Rounded serif wordmark logo 'Aria' on warm cream background (#EDDDD0). Soft rounded serif with gentle curves and warm character. Forest green color (#2D7A3A). Approachable premium food brand. Friendly authority. No icons. Professional brand identity.", "v2-d-aria.png"),
]

# LOGO MARKS with character
marks = [
    ("Logo for 'Olevia' premium food ingredient brand. Combine a hand-drawn olive branch illustration with elegant serif wordmark. Dark olive green (#2D4A22) and warm gold (#D4A574) on cream background (#F5E6C8). Artisanal, warm, like premium olive oil packaging. Vintage inspired but modern. Professional brand identity.", "v2-mark-olevia.png"),
    ("Logo for 'Aria' premium food ingredient brand. Combine a minimal flowing wind/air motif with thin elegant serif wordmark. Dark olive (#2D4A22) and warm amber (#D4A574) on cream (#F5E6C8). Light, airy, natural. Premium food technology brand. Professional brand identity.", "v2-mark-aria.png"),
]

all_dirs = [
    ("A — Warm Serif", a_prompts),
    ("B — Script/Brush", b_prompts),
    ("C — Bold Condensed", c_prompts),
    ("D — Rounded Serif", d_prompts),
    ("Logo Marks", marks),
]

results = {}
for name, prompts in all_dirs:
    print(f"\n{name}")
    for prompt, filename in prompts:
        result = generate(prompt, filename)
        results[filename] = result
        time.sleep(1)

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

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