"""Build ui_language_seed.json from frontend_nyla locale TS files (one-off / CI)."""

from __future__ import annotations

import json
import re
from pathlib import Path

_REPO = Path(__file__).resolve().parents[2]
_SRC = _REPO / "frontend_nyla" / "src" / "locales"
_OUT = _REPO / "gateway" / "modules" / "migration" / "seedData" / "ui_language_seed.json"


def _unescape_ts_single_quoted(raw: str) -> str:
    out: list[str] = []
    i = 0
    while i < len(raw):
        c = raw[i]
        if c == "\\" and i + 1 < len(raw):
            n = raw[i + 1]
            if n == "n":
                out.append("\n")
                i += 2
                continue
            if n == "r":
                out.append("\r")
                i += 2
                continue
            if n == "t":
                out.append("\t")
                i += 2
                continue
            out.append(n)
            i += 2
            continue
        out.append(c)
        i += 1
    return "".join(out)


def _parse_locale(path: Path) -> dict[str, str]:
    text = path.read_text(encoding="utf-8")
    mapping: dict[str, str] = {}
    line_re = re.compile(
        r"^\s*'((?:\\.|[^'])*)':\s*'((?:\\.|[^'])*)'\s*,?\s*(//.*)?$"
    )
    for line in text.splitlines():
        m = line_re.match(line.strip())
        if not m:
            continue
        key = _unescape_ts_single_quoted(m.group(1))
        val = _unescape_ts_single_quoted(m.group(2))
        mapping[key] = val
    return mapping


def main() -> None:
    deMap = _parse_locale(_SRC / "de.ts")
    enMap = _parse_locale(_SRC / "en.ts")
    frMap = _parse_locale(_SRC / "fr.ts")

    dePlain = {v: v for v in deMap.values()}
    enPlain: dict[str, str] = {}
    frPlain: dict[str, str] = {}
    for dotKey, germanText in deMap.items():
        if dotKey in enMap:
            enPlain[germanText] = enMap[dotKey]
        if dotKey in frMap:
            frPlain[germanText] = frMap[dotKey]

    payload = [
        {
            "id": "de",
            "label": "Deutsch",
            "keys": dePlain,
            "status": "complete",
            "isDefault": True,
        },
        {
            "id": "en",
            "label": "English",
            "keys": enPlain,
            "status": "complete",
            "isDefault": False,
        },
        {
            "id": "fr",
            "label": "Français",
            "keys": frPlain,
            "status": "complete",
            "isDefault": False,
        },
    ]
    _OUT.parent.mkdir(parents=True, exist_ok=True)
    _OUT.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
    print("Wrote", _OUT, "keys de/en/fr", len(dePlain), len(enPlain), len(frPlain))


if __name__ == "__main__":
    main()
