#!/usr/bin/env python3
"""Vendor the Lucide icon set into the Triage icon package.

Source: the `lucide-static` npm package (ISC licence — MIT-compatible).
Run once (or when upgrading):

    npm pack lucide-static --pack-destination /tmp
    tar xzf /tmp/lucide-static-*.tgz
    python3 tools/vendor_icons.py --from /tmp/package

Outputs: icons/svg/*.svg (normalized, Triage stroke spec), icons/LICENSE,
icons/PROVENANCE.md. Then run: python3 tools/build_icons.py
"""
import argparse
import json
import os
import re
import shutil
import sys

HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
ICONS = os.path.join(HERE, "icons")

CATEGORIES = {
    "navigation": ["home", "menu", "x", "chevron-up", "chevron-down", "chevron-left", "chevron-right",
                   "arrow-up", "arrow-down", "arrow-left", "arrow-right", "arrow-up-right",
                   "corner-down-right", "external-link", "maximize-2", "minimize-2", "ellipsis",
                   "ellipsis-vertical", "grip-vertical", "panel-left", "layout-grid", "list"],
    "actions": ["plus", "minus", "check", "pencil", "trash-2", "copy", "clipboard", "copy-plus", "save",
                "download", "upload", "share-2", "send", "reply", "forward", "archive", "undo-2", "redo-2",
                "refresh-cw", "rotate-ccw", "filter", "list-filter", "arrow-up-down", "search", "zoom-in",
                "zoom-out", "settings", "sliders-horizontal", "link", "unlink", "pin", "star", "heart",
                "bookmark", "flag", "lock", "unlock", "key-round", "eye", "eye-off", "power", "log-out",
                "log-in", "play", "pause", "circle-stop", "skip-back", "skip-forward", "ban"],
    "status": ["triangle-alert", "circle-alert", "info", "circle-help", "circle-check", "circle-x",
               "circle-plus", "circle-minus"],
    "data": ["file", "file-text", "folder", "folder-open", "database", "server", "cloud", "cloud-upload",
             "hard-drive", "cpu", "terminal", "code", "git-branch", "git-commit-horizontal", "git-merge",
             "package", "box", "layers", "table", "columns-3", "layout-dashboard", "chart-bar", "chart-line",
             "chart-pie", "activity", "calendar", "clock", "timer", "history", "target", "crosshair", "map-pin"],
    "communication": ["mail", "inbox", "message-circle", "message-square", "bell", "bell-off", "at-sign",
                      "phone", "video", "users", "user", "user-plus", "user-minus", "user-round-check", "contact"],
    "media": ["image", "camera", "film", "music", "mic", "mic-off", "volume-2", "volume-x", "headphones",
              "monitor", "smartphone", "tablet", "laptop", "printer", "wifi", "bluetooth", "battery"],
    "editing": ["bold", "italic", "underline", "strikethrough", "align-left", "align-center", "align-right",
                "list-ordered", "list-tree", "indent-decrease", "indent-increase", "type", "quote"],
    "objects": ["toggle-left", "toggle-right", "square", "circle", "dot", "percent", "hash", "tag", "tags"],
    "workflow": ["workflow", "route", "flask-conical", "bot", "blocks", "puzzle", "wrench", "plug", "pipette"],
}

# mail-triage era names → canonical Lucide names (kept for back-compat)
ALIASES = {
    "dashboard": "layout-dashboard", "messages": "mail", "assistant": "message-circle",
    "more": "ellipsis", "rules": "list-filter", "flows": "route", "automation": "workflow",
    "simulator": "flask-conical", "learning": "refresh-cw", "log": "terminal", "accounts": "user-plus",
    "plugins": "plug", "install": "download", "trash": "trash-2", "check-circle": "circle-check",
    "tool": "wrench", "classifier": "filter", "matcher": "search", "draft-provider": "pencil",
    "retriever": "layers", "integration": "blocks",
}

TAGS = {
    "home": "house start", "menu": "hamburger nav", "x": "close dismiss", "search": "find magnifier",
    "settings": "gear preferences", "trash-2": "delete remove", "pencil": "edit write",
    "mail": "email envelope", "terminal": "console log", "flask-conical": "simulate test",
    "refresh-cw": "reload sync", "user-plus": "add account invite", "filter": "funnel classify",
    "layers": "stack retriever", "blocks": "integrate pieces", "wrench": "tool fix",
    "route": "flow path", "workflow": "automation pipeline", "download": "install save",
    "plug": "plugin power", "circle-check": "success done", "bell": "notification alert",
    "triangle-alert": "warning error", "circle-alert": "error danger", "info": "about help",
    "circle-help": "help question", "chart-bar": "graph analytics", "layout-dashboard": "overview panels",
}


def normalize(raw):
    raw = re.sub(r"<!--.*?-->", "", raw, flags=re.S)
    m = re.search(r"<svg[^>]*>", raw)
    if not m:
        raise ValueError("no <svg> tag")
    body = raw[m.end():raw.rindex("</svg>")]
    return re.sub(r"\s+", " ", body).strip()


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--from", dest="src", required=True, help="extracted lucide-static package dir")
    args = ap.parse_args()
    srcdir = os.path.join(args.src, "icons")
    if not os.path.isdir(srcdir):
        print("no icons/ dir under", args.src)
        return 2
    with open(os.path.join(args.src, "package.json")) as fh:
        version = json.load(fh).get("version", "unknown")

    out = os.path.join(ICONS, "svg")
    os.makedirs(out, exist_ok=True)
    count = 0
    for cat, names in CATEGORIES.items():
        for name in names:
            src = os.path.join(srcdir, name + ".svg")
            if not os.path.exists(src):
                print("missing in lucide: %s (%s)" % (name, cat))
                return 1
            body = normalize(open(src).read())
            svg = ('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" '
                   'fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" '
                   'stroke-linejoin="round">%s</svg>\n' % body)
            with open(os.path.join(out, name + ".svg"), "w") as fh:
                fh.write(svg)
            count += 1

    shutil.copy(os.path.join(args.src, "LICENSE"), os.path.join(ICONS, "LICENSE"))
    with open(os.path.join(ICONS, "PROVENANCE.md"), "w") as fh:
        fh.write("# Icon provenance\n\n"
                 "- Set: **Lucide** `lucide-static` v%s (ISC licence, see `LICENSE`).\n"
                 "- Normalization: Triage spec applied — 24×24 viewBox, `fill=none`, `stroke=currentColor`,\n"
                 "  stroke-width 1.7, round caps/joins. Path data unchanged from upstream.\n"
                 "- Curated to %d glyphs in %d categories (`tools/vendor_icons.py` holds the list).\n"
                 "- Original mail-triage names are preserved as aliases (`tools/build_icons.py`).\n"
                 "- Regenerate: `npm pack lucide-static`, extract, `python3 tools/vendor_icons.py --from <dir>`,\n"
                 "  then `python3 tools/build_icons.py`.\n"
                 % (version, count, len(CATEGORIES)))
    print("vendored %d icons from lucide-static %s" % (count, version))
    return 0


if __name__ == "__main__":
    sys.exit(main())
