#!/usr/bin/env python3
"""Generate 20 coloring book images via AIML API."""
import json, os, time, urllib.request, urllib.error, pathlib

API_KEY = os.environ["AIMLAPI_API_KEY"]
OUT = pathlib.Path("/home/node/.openclaw/workspace/books/animali-del-bosco/images")
OUT.mkdir(parents=True, exist_ok=True)

ANIMALS = [
    # Italian name, English description for prompt
    ("volpe", "A cute smiling fox sitting in the forest. Simple thick black outline, clean line art, no shading, white background, very simple shapes for a coloring book for toddlers 3-4 years old."),
    ("riccio", "A cute smiling hedgehog with simple spikes. Thick black outline, clean line art, no shading, white background, very simple shapes for a coloring book page for toddlers 3-4 years old."),
    ("gufo", "A cute smiling owl sitting on a thick tree branch. Thick black outline, clean line art, no shading, white background, simple shapes for a coloring book page for toddlers 3-4 years old."),
    ("scoiattolo", "A cute smiling squirrel holding a big acorn. Thick black outline, clean line art, no shading, white background, simple shapes for a coloring book page for toddlers 3-4 years old."),
    ("cervo", "A cute baby deer with big eyes and small antlers standing in grass. Thick black outline, clean line art, no shading, white background, simple shapes for a coloring book page for toddlers 3-4 years old."),
    ("coniglietto", "A cute bunny rabbit with long ears sitting on a mushroom. Thick black outline, clean line art, no shading, white background, simple shapes for a coloring book page for toddlers 3-4 years old."),
    ("orso", "A cute friendly bear cub standing on two legs and waving. Thick black outline, clean line art, no shading, white background, simple shapes for a coloring book page for toddlers 3-4 years old."),
    ("lupo", "A cute cartoon wolf howling at the moon. Thick black outline, clean line art, no shading, white background, simple shapes for a coloring book page for toddlers 3-4 years old."),
    ("cinghiale", "A cute wild boar with a small curly tail walking in the forest. Thick black outline, clean line art, no shading, white background, simple shapes for a coloring book page for toddlers 3-4 years old."),
    ("lontra", "A cute otter swimming in a small river with a fish. Thick black outline, clean line art, no shading, white background, simple shapes for a coloring book page for toddlers 3-4 years old."),
    ("tasso", "A cute badger with stripes on its face standing next to a tree. Thick black outline, clean line art, no shading, white background, simple shapes for a coloring book page for toddlers 3-4 years old."),
    ("lepre", "A cute hare with long ears hopping in a meadow. Thick black outline, clean line art, no shading, white background, simple shapes for a coloring book page for toddlers 3-4 years old."),
    ("scoiattolo_volante", "A cute flying squirrel gliding between two trees. Thick black outline, clean line art, no shading, white background, simple shapes for a coloring book page for toddlers 3-4 years old."),
    ("civetta", "A cute little owl with big round eyes on a fence post. Thick black outline, clean line art, no shading, white background, simple shapes for a coloring book page for toddlers 3-4 years old."),
    ("pettirosso", "A cute robin bird with a red chest sitting on a branch. Thick black outline, clean line art, no shading, white background, simple shapes for a coloring book page for toddlers 3-4 years old."),
    ("lumaca", "A cute snail with a curly shell crawling on a leaf. Thick black outline, clean line art, no shading, white background, simple shapes for a coloring book page for toddlers 3-4 years old."),
    ("topo", "A cute field mouse holding a piece of cheese. Thick black outline, clean line art, no shading, white background, simple shapes for a coloring book page for toddlers 3-4 years old."),
    ("puzzola", "A cute skunk with a big fluffy tail walking in the woods. Thick black outline, clean line art, no shading, white background, simple shapes for a coloring book page for toddlers 3-4 years old."),
    ("donnola", "A cute weasel peeking out from behind a log. Thick black outline, clean line art, no shading, white background, simple shapes for a coloring book page for toddlers 3-4 years old."),
    ("biscia", "A cute smiling little snake curling around a flower. Thick black outline, clean line art, no shading, white background, simple shapes for a coloring book page for toddlers 3-4 years old."),
]

def generate(name, prompt):
    payload = json.dumps({
        "model": "flux/schnell",
        "prompt": prompt,
        "n": 1,
        "size": "1024x1024",
    }).encode("utf-8")
    
    req = urllib.request.Request(
        "https://api.aimlapi.com/v1/images/generations",
        data=payload,
        headers={
            "Authorization": f"Bearer {API_KEY}",
            "Content-Type": "application/json",
            "Accept": "application/json",
        },
        method="POST",
    )
    
    for attempt in range(3):
        try:
            with urllib.request.urlopen(req, timeout=60) as resp:
                data = json.loads(resp.read())
                url = data["data"][0]["url"]
                # Download the image
                img_req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
                with urllib.request.urlopen(img_req) as img_resp:
                    path = OUT / f"{name}.png"
                    path.write_bytes(img_resp.read())
                    print(f"  ✅ {name}.png")
                    return True
        except Exception as e:
            print(f"  ❌ Attempt {attempt+1} failed for {name}: {e}")
            time.sleep(2)
    return False

print("🎨 Generating 20 coloring book images...")
success = 0
for i, (name, prompt) in enumerate(ANIMALS, 1):
    print(f"[{i}/20] {name}...")
    if generate(name, prompt):
        success += 1
    time.sleep(1)  # Rate limiting

print(f"\n✅ Done! {success}/20 images generated in {OUT}")
