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"
templates_dir = webapp_dir / "templates"
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())

patterns = {
    "data-i18n": re.compile(r'data-i18n=["\']([a-zA-Z0-9_-]+)["\']'),
    "data-i18n-html": re.compile(r'data-i18n-html=["\']([a-zA-Z0-9_-]+)["\']'),
    "data-i18n-placeholder": re.compile(r'data-i18n-placeholder=["\']([a-zA-Z0-9_-]+)["\']'),
    "data-tooltip-title-key": re.compile(r'data-tooltip-title-key=["\']([a-zA-Z0-9_-]+)["\']'),
    "data-tooltip-desc-key": re.compile(r'data-tooltip-desc-key=["\']([a-zA-Z0-9_-]+)["\']'),
    "data-i18n-tooltip-title": re.compile(r'data-i18n-tooltip-title=["\']([a-zA-Z0-9_-]+)["\']'),
    "data-i18n-tooltip-desc": re.compile(r'data-i18n-tooltip-desc=["\']([a-zA-Z0-9_-]+)["\']'),
    "I18N.t": re.compile(r'(?:I18N|FreeExileI18n)\.t\(["\']([a-zA-Z0-9_-]+)["\']'),
    "t_func": re.compile(r'\bt\(["\']([a-zA-Z0-9_-]+)["\']')
}

all_refs = {}
for html_file in templates_dir.glob("*.html"):
    content = html_file.read_text(encoding="utf-8")
    for pat_name, p in patterns.items():
        for m in p.finditer(content):
            k = m.group(1)
            all_refs.setdefault(k, []).append((str(html_file.name), pat_name))

print(f"Total distinct keys found in templates/*.html: {len(all_refs)}")
missing_keys_in_catalog = set(all_refs.keys()) - all_catalog_keys
print(f"Keys in templates but MISSING from I18N_CATALOG: {len(missing_keys_in_catalog)}")
for k in sorted(missing_keys_in_catalog):
    print(f"   Missing: {k} -> {all_refs[k]}")

# Also check for buttons in templates that don't have data-i18n:
print("\n--- Buttons and Tabs in templates without data-i18n ---")
btn_pattern = re.compile(r'<button[^>]*>(.*?)</button>', re.DOTALL)
for html_file in sorted(templates_dir.glob("*.html")):
    content = html_file.read_text(encoding="utf-8")
    for m in btn_pattern.finditer(content):
        btn_tag = m.group(0)
        btn_text = re.sub(r'<[^>]+>', '', m.group(1)).strip()
        if 'data-i18n' not in btn_tag and btn_text and not btn_text.isdigit() and len(btn_text) > 1:
            # check if it has parentheses A (B) or is long
            if "(" in btn_text or len(btn_text.split()) > 2:
                print(f"[{html_file.name}] Unlocalized/Long button: '{btn_text}'")

