import json
import re
import sys
from pathlib import Path
import subprocess

sys.stdout.reconfigure(encoding='utf-8')

root = Path(r"c:\Projects\FreeExile")
catalog_file = root / "client" / "webapp" / "js" / "data" / "i18n_catalog.js"
escaped_path = str(catalog_file).replace("\\", "/")

node_script = """
const fs = require('fs');
const code = fs.readFileSync('""" + escaped_path + """', 'utf-8');
const fakeWindow = {};
const fn = new Function('window', code + '; return I18N_CATALOG;');
const catalog = fn(fakeWindow);
console.log(JSON.stringify(catalog));
"""

res = subprocess.run(["node", "-e", node_script], capture_output=True, encoding="utf-8", check=True)
catalog = json.loads(res.stdout)

all_keys = sorted(list(set(k for loc in catalog.values() for k in loc.keys())))

def categorize_key(k):
    if k.endswith("_name"):
        return "NPC_OR_CHAR_NAME"
    elif k.endswith("_title") and not k.startswith("tooltip_") and not k.startswith("modal_"):
        return "NPC_TITLE"
    elif k.endswith("_service"):
        return "NPC_SERVICE"
    elif k.startswith("tooltip_") and k.endswith("_title"):
        return "TOOLTIP_TITLE"
    elif k.startswith("tooltip_") and k.endswith("_desc"):
        return "TOOLTIP_DESC"
    elif k.startswith("modal_"):
        return "MODAL_HEADER"
    elif k.startswith("interaction_") or k.startswith("portal_") or k in ["dodge", "buyout", "agent_btn_revoke"]:
        return "ACTION_OR_INTERACTION"
    elif k.startswith("skill_"):
        return "SKILL_LABEL"
    elif k.startswith("mob_") or k.startswith("hound_"):
        return "MONSTER_NAME"
    elif k.startswith("vault_tab_") or k.startswith("shop_tab_"):
        return "TAB_OR_CURRENCY_LABEL"
    elif k.startswith("agent_stance_") or k.startswith("telemetry_"):
        return "TELEMETRY_OR_STANCE"
    elif k.startswith("notice_"):
        return "NOTICE"
    elif k.startswith("dialogue_node_"):
        return "DIALOGUE_BODY"
    elif k.startswith("dialogue_choice_") or k.startswith("dialogue_btn_") or k == "dialogue_select":
        return "DIALOGUE_CHOICE_OR_BTN"
    else:
        return "OTHER"

key_categories = {}
for k in all_keys:
    cat = categorize_key(k)
    key_categories.setdefault(cat, []).append(k)

short_ui_cats = [
    "NPC_OR_CHAR_NAME", "NPC_TITLE", "NPC_SERVICE", "TOOLTIP_TITLE",
    "MODAL_HEADER", "ACTION_OR_INTERACTION", "SKILL_LABEL",
    "TAB_OR_CURRENCY_LABEL", "TELEMETRY_OR_STANCE", "DIALOGUE_CHOICE_OR_BTN"
]

dict_loc = catalog.get("vi", {})
print(f"Total keys in VI: {len(dict_loc)}")
for cat_name in short_ui_cats:
    keys = key_categories.get(cat_name, [])
    for k in keys:
        if k in dict_loc:
            val = dict_loc[k]
            clean_val = re.sub(r"[\U00010000-\U0010ffff\u2600-\u27ff]", "", val).strip()
            words = clean_val.split()
            if len(words) > 2:
                print(f"[{cat_name}] {k}: '{val}' ({len(words)} words)")
