#!/usr/bin/env python3
"""
Generate a case mapping file of lowercase to uppercase characters
based on the supported UI glyph definitions in text_tr1.def and text_tr2.def.
"""
import ast
import re
import sys
from pathlib import Path

# HACK: Ensure the shared module is visible for this script.
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

from shared.glyph_mapping import Glyph, get_glyph_map
from shared.paths import PROJECT_PATHS, SHARED_SRC_DIR


def main() -> None:
    ui_dir = SHARED_SRC_DIR / "game/ui"

    glyphs: list[Glyph] = []
    for project in PROJECT_PATHS.values():
        glyphs += get_glyph_map(project.data_dir / "glyphs")

    supported = set(g.text for g in glyphs)
    lowers = [c for c in supported if len(c) == 1 and c.islower()]
    mapping: list[tuple[str, str]] = []
    for c in sorted(lowers, key=lambda x: ord(x)):
        up = c.upper()
        if len(up) == 1 and up in supported:
            mapping.append((c, up))

    out_path = SHARED_SRC_DIR / "strings/case_map.def"
    lines: list[str] = [
        "// This file is autogenerated - do not edit.",
        "// See tools/glyphs/generate_case_map for details.",
        "",
    ]
    for low, up in mapping:
        lit_low = low.replace("\\", "\\\\").replace('"', '\\"')
        lit_up = up.replace("\\", "\\\\").replace('"', '\\"')
        lines.append(f'X_CASE_MAP("{lit_low}", "{lit_up}")')

    out_path.write_text("\n".join(lines) + "\n", encoding="utf-8")


if __name__ == "__main__":
    main()
