#!/usr/bin/env python3
"""Build the Triage icon artifacts from icons/svg/*.svg.

Source of truth: the individual SVG files (vendored from Lucide + normalized).
Outputs:
    icons/sprite.svg    <symbol> sheet for <use> consumers
    icons/icons.json    registry: names, categories, tags, aliases, path bodies

Run:  python3 tools/build_icons.py [--check]
"""
import argparse
import json
import os
import re
import sys

HERE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TOOLS = os.path.dirname(os.path.abspath(__file__))
ICONS = os.path.join(HERE, "icons")
sys.path.insert(0, TOOLS)
from vendor_icons import ALIASES, CATEGORIES, TAGS  # noqa: E402


def load_version():
    with open(os.path.join(HERE, "VERSION")) as fh:
        return fh.read().strip()


def read_body(path):
    raw = open(path).read()
    m = re.search(r"<svg[^>]*>", raw)
    return raw[m.end():raw.rindex("</svg>")].strip()


def build():
    svgdir = os.path.join(ICONS, "svg")
    cats = {}
    for cat, names in CATEGORIES.items():
        for n in names:
            cats[n] = cat
    icons = []
    bodies = {}
    problems = []
    for name in sorted(cats):
        path = os.path.join(svgdir, name + ".svg")
        if not os.path.exists(path):
            problems.append("missing file: %s" % name)
            continue
        raw = open(path).read()
        if 'viewBox="0 0 24 24"' not in raw:
            problems.append("%s: viewBox is not 24" % name)
        body = read_body(path)
        if not body:
            problems.append("%s: empty body" % name)
        bodies[name] = body
        icons.append({"name": name, "category": cats[name],
                      "tags": TAGS.get(name, ""), "aliases": [],
                      "body": body})

    alias_map = {}
    for alias, target in sorted(ALIASES.items()):
        if target not in bodies:
            problems.append("alias %s -> %s: target missing" % (alias, target))
            continue
        if alias in bodies:
            problems.append("alias %s collides with a canonical name" % alias)
            continue
        alias_map[alias] = target
        for entry in icons:
            if entry["name"] == target:
                entry["aliases"].append(alias)

    # duplicate path detection (F9): canonical glyphs must be unique
    seen = {}
    for name, body in bodies.items():
        key = re.sub(r"\s+", " ", body)
        if key in seen:
            problems.append("duplicate path data: %s == %s" % (seen[key], name))
        else:
            seen[key] = name

    symbols = "".join('<symbol id="i-%s" viewBox="0 0 24 24">%s</symbol>\n' % (i["name"], i["body"])
                      for i in icons)
    sprite = ('<svg xmlns="http://www.w3.org/2000/svg" style="display:none" aria-hidden="true">\n'
              + symbols + "</svg>\n")
    registry = {
        "$comment": "Triage icon registry — generated from icons/svg/*.svg by tools/build_icons.py. "
                    "Set: Lucide (ISC). Grid 24, stroke 1.7, currentColor. 'body' is the inner SVG markup.",
        "version": load_version(),
        "license": "ISC",
        "grid": 24,
        "stroke": 1.7,
        "count": len(icons),
        "aliases": alias_map,
        "icons": icons,
    }
    return sprite, json.dumps(registry, indent=2) + "\n", problems


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--check", action="store_true")
    args = ap.parse_args()
    sprite, registry, problems = build()
    if problems:
        for p in problems:
            print("ICON PROBLEM:", p)
        return 1
    sprite_path = os.path.join(ICONS, "sprite.svg")
    json_path = os.path.join(ICONS, "icons.json")
    if args.check:
        ok = True
        for path, expected in ((sprite_path, sprite), (json_path, registry)):
            current = open(path).read() if os.path.exists(path) else ""
            if current != expected:
                print("%s is OUT OF SYNC — run: python3 tools/build_icons.py" % os.path.relpath(path, HERE))
                ok = False
        if ok:
            n = len(json.loads(registry)["icons"])
            print("icons in sync (%d glyphs, %d aliases)" % (n, len(json.loads(registry)["aliases"])))
        return 0 if ok else 1
    with open(sprite_path, "w") as fh:
        fh.write(sprite)
    with open(json_path, "w") as fh:
        fh.write(registry)
    data = json.loads(registry)
    print("built %d icons, %d aliases -> icons/sprite.svg, icons/icons.json"
          % (len(data["icons"]), len(data["aliases"])))
    return 0


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