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

# Check completeness matrix
locales = ["vi", "en", "zh", "ja", "ko", "th", "de", "ru", "es"]
matrix = {}
for k in all_keys:
    matrix[k] = {loc: (k in catalog.get(loc, {})) for loc in locales}

# Print keys that have partial coverage
partial_keys = [k for k, loc_map in matrix.items() if not all(loc_map.values())]
print(f"Total keys: {len(all_keys)}")
print(f"Keys with 100% coverage across all 9 languages: {len(all_keys) - len(partial_keys)}")
print(f"Keys with PARTIAL coverage (missing in at least one language): {len(partial_keys)}")

# Let's inspect the partial keys and which languages are missing them
print("\n=== PARTIAL KEYS BREAKDOWN ===")
for k in partial_keys:
    missing_locs = [loc for loc in locales if not matrix[k][loc]]
    present_locs = [loc for loc in locales if matrix[k][loc]]
    print(f"Key '{k}': Present in {present_locs} | Missing in {missing_locs}")

