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())))

# Categories of 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)

print("=== KEY CATEGORIES ===")
for cat, keys in sorted(key_categories.items()):
    print(f"{cat}: {len(keys)} keys")

# Function to count words
# In Vietnamese, English, German, Russian, Spanish: space-separated words.
# In Chinese and Japanese: characters or morphs. For Chinese/Japanese, 1-2 words is typically 2-4 characters or 1-2 words.
# In Thai: no spaces typically, needs tokenization or character count.
# For Western / space-delimited languages:
def count_words(text, loc):
    # strip leading emojis and punctuation
    cleaned = re.sub(r"^[^\w\s]+", "", text.strip())
    cleaned = re.sub(r"[^\w\s]+$", "", cleaned)
    # remove parenthetical info for word count test or keep it?
    # Requirement: "Identify all entries across all 9 languages that exceed 1-2 words or contain bilingual strings A (B)"
    if loc in ['zh', 'ja']:
        # in CJK, each word is typically 1-2 characters, so <= 4 chars is ~1-2 words, > 4 chars is > 2 words
        # Or count characters
        return len([c for c in cleaned if not c.isspace()])
    elif loc == 'ko':
        # Korean uses spaces
        words = [w for w in cleaned.split() if w]
        return len(words)
    elif loc == 'th':
        # Thai without spaces: approximate word count or character count
        return len(cleaned)
    else:
        words = [w for w in cleaned.split() if w]
        return len(words)

# Audit short UI categories:
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"
]

print("\n=== SHORT UI STRINGS AUDIT (> 2 WORDS) ===")
# Let's inspect vi and en first
for loc in ["vi", "en", "zh", "ja", "ko", "th", "de", "ru", "es"]:
    long_entries = []
    dict_loc = catalog.get(loc, {})
    for cat_name in short_ui_cats:
        for k in key_categories.get(cat_name, []):
            if k in dict_loc:
                val = dict_loc[k]
                # Clean out emoji
                clean_val = re.sub(r"[\U00010000-\U0010ffff\u2600-\u27ff]", "", val).strip()
                words = clean_val.split()
                if loc in ['vi', 'en', 'de', 'ru', 'es', 'ko']:
                    if len(words) > 2:
                        long_entries.append((cat_name, k, val, len(words)))
                elif loc in ['zh', 'ja']:
                    if len(clean_val) > 4: # more than 4 chars is usually 3+ words or long phrase
                        long_entries.append((cat_name, k, val, len(clean_val)))
                elif loc == 'th':
                    if len(clean_val) > 12:
                        long_entries.append((cat_name, k, val, len(clean_val)))
    print(f"\nLocale {loc}: {len(long_entries)} UI entries exceeding brevity threshold")
    for cat_name, k, val, cnt in long_entries[:20]:
        print(f"   [{cat_name}] {k}: '{val}' ({cnt} units)")
    if len(long_entries) > 20:
        print(f"   ... and {len(long_entries) - 20} more")
