#!/usr/bin/env python3
"""Genera cpp/functions/core/icons_tabler.h a partir del CSS oficial de Tabler.

Uso:
    cd cpp/vendor/tabler-icons
    python3 gen_header.py

Lee tabler-icons.css (descargado desde el npm package @tabler/icons-webfont) y
escribe ../../functions/core/icons_tabler.h con un #define TI_<NAME> "<utf8>"
para cada glyph.
"""
import re
import sys
from pathlib import Path

HERE = Path(__file__).parent
CSS = HERE / "tabler-icons.css"
OUT = HERE / ".." / ".." / "functions" / "core" / "icons_tabler.h"
OUT = OUT.resolve()

VERSION_RE = re.compile(r"Tabler Icons\s+([\d.]+)")
RULE_RE = re.compile(r"\.ti-([a-z0-9-]+):before\s*\{\s*content:\s*\"\\([0-9a-fA-F]+)\"")


def to_utf8_escape(codepoint: int) -> str:
    """Devuelve la cadena UTF-8 del codepoint en hex escapado para C strings."""
    return "".join(f"\\x{b:02x}" for b in chr(codepoint).encode("utf-8"))


def name_to_macro(name: str) -> str:
    return "TI_" + name.upper().replace("-", "_")


def main() -> int:
    if not CSS.exists():
        sys.stderr.write(f"missing {CSS}\n")
        return 1

    text = CSS.read_text(encoding="utf-8")
    m = VERSION_RE.search(text)
    version = m.group(1) if m else "unknown"

    entries = []
    seen = set()
    for name, hexcp in RULE_RE.findall(text):
        macro = name_to_macro(name)
        if macro in seen:
            continue
        seen.add(macro)
        cp = int(hexcp, 16)
        entries.append((macro, cp, to_utf8_escape(cp)))

    entries.sort(key=lambda e: e[0])

    lines = [
        "#pragma once",
        "",
        "// Tabler Icons codepoints — generado por cpp/vendor/tabler-icons/gen_header.py",
        f"// Version: {version}",
        "// Fuente: https://github.com/tabler/tabler-icons (MIT)",
        "//",
        "// Uso:",
        "//   #include \"core/icons_tabler.h\"",
        "//   icon_button(\"##rl\", TI_REFRESH, \"Reload\");",
        "//   button(TI_DEVICE_FLOPPY \" Save\", V::Primary);",
        "//",
        "// El glyph SOLO se renderiza si la fuente Tabler esta cargada (mergeada en el",
        "// atlas de ImGui via fn_ui::load_default_fonts). Sin esa carga, los TI_* salen",
        "// como cuadritos vacios.",
        "",
        f"#define TI_FONT_VERSION \"{version}\"",
        "#define TI_ICON_MIN 0xE000",
        "#define TI_ICON_MAX 0xF8FF",
        "",
    ]
    for macro, cp, utf8 in entries:
        lines.append(f"#define {macro:<48} \"{utf8}\" // U+{cp:04X}")
    lines.append("")

    OUT.write_text("\n".join(lines), encoding="utf-8")
    print(f"wrote {OUT} ({len(entries)} icons, version {version})")
    return 0


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