#!/usr/bin/env python3
"""design/render/glyphs.js is the one source for the Vanta glyph set; this
writes the same paths into VantaCore as Kotlin so the ROM and the browser
render draw identical icons. --check fails on drift."""
import os, re, sys

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SRC = os.path.join(ROOT, "design/render/glyphs.js")
DST = os.path.join(ROOT, "vendor/vanta/packages/VantaCore/src/com/failure/vanta/core/Glyphs.kt")


def render():
    js = open(SRC).read()
    body = js.split("export const G = {", 1)[1].split("};", 1)[0]
    pairs = re.findall(r"^\s*(\w+):\s*'([^']+)',", body, re.M)
    mask = re.search(r"export const MASK = '([^']+)'", js).group(1)
    L = ["// GENERATED by tools/gen_glyphs.py from design/render/glyphs.js. Do not edit.",
         "package com.failure.vanta.core", "", "object Glyphs {",
         f'    const val MASK = "{mask}"', ""]
    for k, d in pairs:
        L.append(f'    const val {k.upper()} = "{d}"')
    L.append("")
    L.append("    val all = mapOf(" + ", ".join(f'"{k}" to {k.upper()}' for k, _ in pairs) + ")")
    L.append("}")
    return "\n".join(L) + "\n", len(pairs)


def main():
    text, n = render()
    cur = open(DST).read() if os.path.exists(DST) else None
    if "--check" in sys.argv:
        if cur != text:
            print("gen_glyphs: Glyphs.kt drifted from glyphs.js"); sys.exit(1)
        print(f"gen_glyphs: {n} glyphs in sync"); return
    open(DST, "w").write(text)
    print(f"gen_glyphs: wrote {n} glyphs")


if __name__ == "__main__":
    main()
