#!/usr/bin/env python3
"""Resolve open-license icons for the 3rd-grade book vocabulary (Iconify)."""
import os, subprocess, sys, time

HERE = os.path.dirname(os.path.abspath(__file__))
ICON_DIR = os.path.join(HERE, "icons")
os.makedirs(ICON_DIR, 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")

# key -> ordered candidate iconify ids
CAND = {
    # Unit 1 - My Classroom
    "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:notebook", "noto:notebook"],
    "ruler":      ["fluent-emoji-flat:straight-ruler", "noto:straight-ruler"],
    "eraser":     ["fluent-emoji-flat:eraser", "noto:eraser"],
    "schoolbag":  ["fluent-emoji-flat:backpack", "noto:backpack"],
    "desk":       ["noto:desk", "openmoji:desk", "fluent-emoji-flat:desk"],
    "chair":      ["fluent-emoji-flat:chair", "noto:chair"],
    "board":      ["noto:chalkboard", "openmoji:blackboard", "fluent-emoji-flat:chalkboard"],
    "door":       ["fluent-emoji-flat:door", "noto:door"],
    "window":     ["fluent-emoji-flat:window", "noto:window"],
    "numbers":    ["fluent-emoji-flat:input-numbers", "noto:input-numbers"],
    # Unit 2 - My Family and Friends
    "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:doctor"],
    "nurse":      ["fluent-emoji-flat:nurse", "noto:nurse"],
    "friend":     ["fluent-emoji-flat:people-holding-hands", "noto:handshake"],
    # Unit 3 - Body and Appearance
    "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"],
    "hair":       ["fluent-emoji-flat:person-getting-haircut", "noto:person-getting-haircut"],
    "monster":    ["fluent-emoji-flat:alien-monster", "noto:alien-monster"],
    "face":       ["fluent-emoji-flat:grinning-face", "noto:grinning-face"],
    # Unit 4 - Colours and Clothes
    "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"],
    # Unit 5 - My Home
    "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"],
    "sofa":       ["fluent-emoji-flat:couch-and-lamp", "noto:couch-and-lamp"],
    "bed":        ["fluent-emoji-flat:bed", "noto:bed"],
    # Unit 6 - Animals
    "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"],
    # Unit 7 - Food
    "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:egg"],
    "water":      ["fluent-emoji-flat:droplet", "noto:droplet"],
    "cake":       ["fluent-emoji-flat:shortcake", "noto:shortcake"],
    "fishfood":   ["fluent-emoji-flat:fish", "noto:fish"],
    # Unit 8 - My Toys
    "ball":       ["fluent-emoji-flat:person-bouncing-ball", "noto:softball"],
    "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"],
    # Unit 9 - At the Playground
    "slide":      ["fluent-emoji-flat:playground-slide", "noto:playground-slide"],
    "seesaw":     ["fluent-emoji-flat:playground-slide", "noto:playground-slide"],
    "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"],
    "skip":       ["fluent-emoji-flat:person-bouncing-ball", "noto:person-bouncing-ball"],
    "play":       ["fluent-emoji-flat:person-bouncing-ball", "noto:person-bouncing-ball"],
    "happy":      ["fluent-emoji-flat:grinning-face", "noto:grinning-face"],
}

def fetch(iconify_id, key):
    svg = os.path.join(ICON_DIR, key + ".svg")
    png = os.path.join(ICON_DIR, key + ".png")
    url = f"https://api.iconify.design/{iconify_id}.svg?height=512"
    subprocess.run(["curl", "-sL", "-A", UA, "-H", "Accept: image/svg+xml",
                    "-o", svg, url], check=True, capture_output=True)
    try:
        data = open(svg, "rb").read()
    except Exception:
        return False
    if b"<svg" not in data:
        return False
    r = subprocess.run(["rsvg-convert", "-w", "256", "-h", "256", svg, "-o", png],
                       capture_output=True)
    return r.returncode == 0 and os.path.exists(png)

resolved, failed = {}, []
for key, cands in CAND.items():
    if os.path.exists(os.path.join(ICON_DIR, key + ".png")):
        resolved[key] = "cached"; continue
    got = None
    for cid in cands:
        for attempt in range(4):
            if fetch(cid, key):
                got = cid; break
            time.sleep(3.0)
        if got:
            break
        time.sleep(1.0)
    if got:
        resolved[key] = got
    else:
        failed.append(key)
    time.sleep(2.5)

print("RESOLVED:", len(resolved))
for k, v in sorted(resolved.items()):
    print(f"  {k}: {v}")
print("FAILED:", failed)
