#!/usr/bin/env python3
"""Paced downloader for Fluent Emoji Flat icons (Iconify) -> PNG.
Safe against Cloudflare rate limits: 2.5s pacing, retries, skips cached files."""
import os, subprocess, time

HERE = os.path.dirname(os.path.abspath(__file__))
OUT = os.path.join(HERE, "icons")
os.makedirs(OUT, exist_ok=True)
UA = ("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
      "(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")

# name -> list of candidate iconify ids (first that resolves wins)
ICONS = {
 "pen": ["fluent-emoji-flat:pen", "noto:pen"],
 "pencil": ["fluent-emoji-flat:pencil", "noto:pencil"],
 "book": ["fluent-emoji-flat:open-book", "noto:open-book"],
 "notebook": ["fluent-emoji-flat:ledger", "noto:ledger"],
 "ruler": ["fluent-emoji-flat:straight-ruler", "noto:straight-ruler"],
 "eraser": ["fluent-emoji-flat:eraser", "noto:eraser"],
 "schoolbag": ["fluent-emoji-flat:backpack", "noto:backpack"],
 "desk": ["fluent-emoji-flat:desktop-computer", "noto:desktop-computer"],
 "chair": ["fluent-emoji-flat:chair", "noto:chair"],
 "board": ["fluent-emoji-flat:chalkboard", "noto:chalkboard"],
 "door": ["fluent-emoji-flat:door", "noto:door"],
 "window": ["fluent-emoji-flat:window", "noto:window"],
 "numbers": ["fluent-emoji-flat:input-numbers", "noto:input-numbers"],
 "mother": ["fluent-emoji-flat:woman", "noto:woman"],
 "father": ["fluent-emoji-flat:man", "noto:man"],
 "sister": ["fluent-emoji-flat:girl", "noto:girl"],
 "brother": ["fluent-emoji-flat:boy", "noto:boy"],
 "grandmother": ["fluent-emoji-flat:old-woman", "noto:older-person"],
 "grandfather": ["fluent-emoji-flat:old-man", "noto:older-person"],
 "baby": ["fluent-emoji-flat:baby", "noto:baby"],
 "family": ["fluent-emoji-flat:family", "noto:family"],
 "teacher": ["fluent-emoji-flat:teacher", "noto:teacher"],
 "doctor": ["fluent-emoji-flat:health-worker", "noto:health-worker"],
 "nurse": ["fluent-emoji-flat:nurse", "noto:nurse"],
 "friend": ["fluent-emoji-flat:people-holding-hands", "noto:people-holding-hands"],
 "eye": ["fluent-emoji-flat:eye", "noto:eye"],
 "ear": ["fluent-emoji-flat:ear", "noto:ear"],
 "nose": ["fluent-emoji-flat:nose", "noto:nose"],
 "mouth": ["fluent-emoji-flat:mouth", "noto:mouth"],
 "hand": ["fluent-emoji-flat:raised-hand", "noto:raised-hand"],
 "face": ["fluent-emoji-flat:grinning-face", "noto:grinning-face"],
 "monster": ["fluent-emoji-flat:alien-monster", "noto:alien-monster"],
 "haircut": ["fluent-emoji-flat:person-getting-haircut", "noto:person-getting-haircut"],
 "tshirt": ["fluent-emoji-flat:t-shirt", "noto:t-shirt"],
 "trousers": ["fluent-emoji-flat:jeans", "noto:jeans"],
 "dress": ["fluent-emoji-flat:dress", "noto:dress"],
 "shoes": ["fluent-emoji-flat:running-shoe", "noto:running-shoe"],
 "hat": ["fluent-emoji-flat:billed-cap", "noto:billed-cap"],
 "jacket": ["fluent-emoji-flat:coat", "noto:coat"],
 "rainbow": ["fluent-emoji-flat:rainbow", "noto:rainbow"],
 "sun": ["fluent-emoji-flat:sun", "noto:sun"],
 "rain": ["fluent-emoji-flat:cloud-with-rain", "noto:cloud-with-rain"],
 "house": ["fluent-emoji-flat:house", "noto:house"],
 "kitchen": ["fluent-emoji-flat:cooking", "noto:cooking"],
 "bedroom": ["fluent-emoji-flat:bed", "noto:bed"],
 "bathroom": ["fluent-emoji-flat:bathtub", "noto:bathtub"],
 "garden": ["fluent-emoji-flat:potted-plant", "noto:potted-plant"],
 "livingroom": ["fluent-emoji-flat:couch-and-lamp", "noto:couch-and-lamp"],
 "bed": ["fluent-emoji-flat:bed", "noto:bed"],
 "cat": ["fluent-emoji-flat:cat-face", "noto:cat-face"],
 "dog": ["fluent-emoji-flat:dog-face", "noto:dog-face"],
 "bird": ["fluent-emoji-flat:bird", "noto:bird"],
 "fish": ["fluent-emoji-flat:fish", "noto:fish"],
 "horse": ["fluent-emoji-flat:horse-face", "noto:horse-face"],
 "cow": ["fluent-emoji-flat:cow-face", "noto:cow-face"],
 "sheep": ["fluent-emoji-flat:ewe", "noto:ewe"],
 "donkey": ["fluent-emoji-flat:donkey", "noto:donkey"],
 "rabbit": ["fluent-emoji-flat:rabbit-face", "noto:rabbit-face"],
 "bee": ["fluent-emoji-flat:honeybee", "noto:honeybee"],
 "turtle": ["fluent-emoji-flat:turtle", "noto:turtle"],
 "apple": ["fluent-emoji-flat:red-apple", "noto:red-apple"],
 "banana": ["fluent-emoji-flat:banana", "noto:banana"],
 "milk": ["fluent-emoji-flat:glass-of-milk", "noto:glass-of-milk"],
 "bread": ["fluent-emoji-flat:bread", "noto:bread"],
 "cheese": ["fluent-emoji-flat:cheese-wedge", "noto:cheese-wedge"],
 "egg": ["fluent-emoji-flat:cooking", "noto:cooking"],
 "water": ["fluent-emoji-flat:droplet", "noto:droplet"],
 "cake": ["fluent-emoji-flat:shortcake", "noto:shortcake"],
 "orange": ["fluent-emoji-flat:tangerine", "noto:tangerine"],
 "carrot": ["fluent-emoji-flat:carrot", "noto:carrot"],
 "ball": ["fluent-emoji-flat:soccer-ball", "noto:soccer-ball"],
 "doll": ["fluent-emoji-flat:nesting-dolls", "noto:nesting-dolls"],
 "car": ["fluent-emoji-flat:automobile", "noto:automobile"],
 "teddy": ["fluent-emoji-flat:teddy-bear", "noto:teddy-bear"],
 "kite": ["fluent-emoji-flat:kite", "noto:kite"],
 "robot": ["fluent-emoji-flat:robot", "noto:robot"],
 "plane": ["fluent-emoji-flat:airplane", "noto:airplane"],
 "train": ["fluent-emoji-flat:train", "noto:train"],
 "box": ["fluent-emoji-flat:card-file-box", "noto:card-file-box"],
 "puzzle": ["fluent-emoji-flat:puzzle-piece", "noto:puzzle-piece"],
 "run": ["fluent-emoji-flat:person-running", "noto:person-running"],
 "jump": ["fluent-emoji-flat:person-cartwheeling", "noto:person-cartwheeling"],
 "climb": ["fluent-emoji-flat:person-climbing", "noto:person-climbing"],
 "swing": ["fluent-emoji-flat:playground-slide", "noto:playground-slide"],
 "slide": ["fluent-emoji-flat:playground-slide", "noto:playground-slide"],
 "happy": ["fluent-emoji-flat:grinning-face", "noto:grinning-face"],
 "sad": ["fluent-emoji-flat:crying-face", "noto:crying-face"],
 "swim": ["fluent-emoji-flat:person-swimming", "noto:person-swimming"],
 "dance": ["fluent-emoji-flat:woman-dancing", "noto:woman-dancing"],
 "sing": ["fluent-emoji-flat:microphone", "noto:microphone"],
 "eat": ["fluent-emoji-flat:fork-and-knife-with-plate", "noto:fork-and-knife-with-plate"],
 "drink": ["fluent-emoji-flat:cup-with-straw", "noto:cup-with-straw"],
 "sleep": ["fluent-emoji-flat:sleeping-face", "noto:sleeping-face"],
 "read": ["fluent-emoji-flat:open-book", "noto:open-book"],
 "write": ["fluent-emoji-flat:memo", "noto:memo"],
 "draw": ["fluent-emoji-flat:artist-palette", "noto:artist-palette"],
 "listen": ["fluent-emoji-flat:ear", "noto:ear"],
 "speak": ["fluent-emoji-flat:speaking-head", "noto:speaking-head"],
 "count": ["fluent-emoji-flat:abacus", "noto:abacus"],
 "phone": ["fluent-emoji-flat:mobile-phone", "noto:mobile-phone"],
 "clock": ["fluent-emoji-flat:alarm-clock", "noto:alarm-clock"],
 "tv": ["fluent-emoji-flat:television", "noto:television"],
 "lamp": ["fluent-emoji-flat:couch-and-lamp", "noto:couch-and-lamp"],
 "toothbrush": ["fluent-emoji-flat:toothbrush", "noto:toothbrush"],
 "broom": ["fluent-emoji-flat:broom", "noto:broom"],
 "star": ["fluent-emoji-flat:star", "noto:star"],
 "pencilcase": ["fluent-emoji-flat:pencil", "noto:pencil"],
 "bag": ["fluent-emoji-flat:handbag", "noto:handbag"],
 "icecream": ["fluent-emoji-flat:soft-ice-cream", "noto:soft-ice-cream"],
 "hamburger": ["fluent-emoji-flat:hamburger", "noto:hamburger"],
 "pizza": ["fluent-emoji-flat:pizza", "noto:pizza"],
 "tiger": ["fluent-emoji-flat:tiger-face", "noto:tiger-face"],
 "lion": ["fluent-emoji-flat:lion", "noto:lion"],
 "elephant": ["fluent-emoji-flat:elephant", "noto:elephant"],
 "monkey": ["fluent-emoji-flat:monkey-face", "noto:monkey-face"],
 "duck": ["fluent-emoji-flat:duck", "noto:duck"],
 "frog": ["fluent-emoji-flat:frog", "noto:frog"],
 "butterfly": ["fluent-emoji-flat:butterfly", "noto:butterfly"],
 "flower": ["fluent-emoji-flat:blossom", "noto:blossom"],
 "tree": ["fluent-emoji-flat:deciduous-tree", "noto:deciduous-tree"],
 "balloon": ["fluent-emoji-flat:balloon", "noto:balloon"],
 "gift": ["fluent-emoji-flat:wrapped-gift", "noto:wrapped-gift"],
 "music": ["fluent-emoji-flat:musical-notes", "noto:musical-notes"],
 "art": ["fluent-emoji-flat:artist-palette", "noto:artist-palette"],
 "sports": ["fluent-emoji-flat:sports-medal", "noto:sports-medal"],
}

def download(cid):
    svg = os.path.join(OUT, "_tmp.svg")
    subprocess.run(["curl", "-sL", "-A", UA, "-H", "Accept: image/svg+xml",
                    "--max-time", "25", "-o", svg, 
                    f"https://api.iconify.design/{cid}.svg?height=512"],
                   check=False, capture_output=True)
    try:
        data = open(svg, "rb").read()
    except Exception:
        return None
    if b"<svg" not in data[:2000]:
        return None
    return svg

done, fail = [], []
for name, cands in ICONS.items():
    png = os.path.join(OUT, name + ".png")
    if os.path.exists(png):
        done.append(name); continue
    ok = False
    for cid in cands:
        for attempt in range(5):
            svg = download(cid)
            if svg:
                r = subprocess.run(["rsvg-convert", "-w", "256", "-h", "256",
                                    svg, "-o", png], capture_output=True)
                if r.returncode == 0 and os.path.exists(png):
                    ok = True; break
            time.sleep(4.0)
        if ok: break
        time.sleep(1.0)
    (done if ok else fail).append(name)
    if not ok:
        print(f"FAIL {name}", flush=True)
    time.sleep(2.5)

print(f"DONE {len(done)} FAIL {len(fail)}", flush=True)
if fail:
    print("failed:", " ".join(fail), flush=True)
