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

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

root = Path(r"c:\Projects\FreeExile")
webapp_dir = root / "client" / "webapp"
catalog_file = webapp_dir / "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_catalog_keys = set(k for loc in catalog.values() for k in loc.keys())

# Regex patterns to search in webapp files
patterns = [
    re.compile(r'data-i18n=["\']([a-zA-Z0-9_-]+)["\']'),
    re.compile(r'data-i18n-html=["\']([a-zA-Z0-9_-]+)["\']'),
    re.compile(r'data-i18n-placeholder=["\']([a-zA-Z0-9_-]+)["\']'),
    re.compile(r'data-i18n-tooltip-title=["\']([a-zA-Z0-9_-]+)["\']'),
    re.compile(r'data-i18n-tooltip-desc=["\']([a-zA-Z0-9_-]+)["\']'),
    re.compile(r'data-tooltip-title-key=["\']([a-zA-Z0-9_-]+)["\']'),
    re.compile(r'data-tooltip-desc-key=["\']([a-zA-Z0-9_-]+)["\']'),
    re.compile(r'(?:I18N|FreeExileI18n)\.t\(["\']([a-zA-Z0-9_-]+)["\']'),
    re.compile(r'\bt\(["\']([a-zA-Z0-9_-]+)["\']'),
]

found_keys = {}
for ext in ["*.html", "*.js"]:
    for fpath in webapp_dir.rglob(ext):
        if "i18n_catalog.js" in str(fpath):
            continue
        try:
            content = fpath.read_text(encoding="utf-8")
        except Exception:
            continue
        for p in patterns:
            for match in p.finditer(content):
                k = match.group(1)
                found_keys.setdefault(k, []).append((str(fpath.relative_to(root)), match.start()))

print(f"Total distinct keys referenced in client/webapp code/HTML: {len(found_keys)}")
missing_from_catalog = set(found_keys.keys()) - all_catalog_keys
print(f"Keys referenced in code but MISSING from I18N_CATALOG: {len(missing_from_catalog)}")
for k in sorted(missing_from_catalog):
    refs = [r[0] for r in found_keys[k]]
    print(f"   Missing key: '{k}' (referenced in {refs})")

in_catalog_not_found = all_catalog_keys - set(found_keys.keys())
print(f"\nKeys in catalog but not explicitly found by static regex: {len(in_catalog_not_found)}")
for k in sorted(in_catalog_not_found)[:20]:
    print(f"   Dynamic or unused catalog key: '{k}'")
if len(in_catalog_not_found) > 20:
    print(f"   ... and {len(in_catalog_not_found) - 20} more")
