import json
import re
import sys
from pathlib import Path
from generate_catalog import ENTRIES

locales = ["vi", "en", "zh", "ja", "ko", "th", "de", "ru", "es"]

# Check all 143 entries
assert len(ENTRIES) == 143

def escape_val(v: str) -> str:
    # Escape { and } as \u007b and \u007d so regex [^}]+ doesn't stop prematurely
    v_escaped = v.replace("{", "\\u007b").replace("}", "\\u007d")
    # Also escape double quotes
    v_escaped = v_escaped.replace('\\"', '"').replace('"', '\\"')
    return f'"{v_escaped}"'

out_lines = [
    "// =============================================================================",
    "// FREEEXILE: 9-LANGUAGE MASTER LOCALIZATION CATALOG (DATA REPOSITORY)",
    "// Theme: CỔ VÕ HOANG DÃ & HẮC ÁM LƯU ĐÀY (Grimdark Savage Primal Exile ARPG)",
    "// Compliant with docs/standards/GLOBAL_LOCALIZATION_DICTIONARY.md",
    "// Compact 9-Language Dictionary Structure (<= 700 lines hygiene compliance)",
    "// =============================================================================",
    "",
    "const I18N_CATALOG = {"
]

for l_idx, loc in enumerate(locales):
    out_lines.append(f"  {loc}: {{")
    
    # We want to pack keys reasonably: 2 to 3 keys per line for short entries, 1 for long entries
    # Group entries into chunks:
    current_line = "    "
    for e_idx, entry in enumerate(ENTRIES):
        k = entry[0]
        val = escape_val(entry[l_idx + 1])
        item_str = f"{k}: {val}"
        
        # Check if last item in this locale
        is_last = (e_idx == len(ENTRIES) - 1)
        sep = "" if is_last else ", "
        
        # Check line length if we append item_str + sep
        # Descriptions or notices: put on own line if long (> 80 chars)
        if len(current_line.strip()) > 0 and (len(current_line) + len(item_str) > 130 or k.endswith("_desc") or k.startswith("dialogue_node_") or len(item_str) > 75):
            out_lines.append(current_line.rstrip())
            current_line = "    " + item_str + sep
        else:
            current_line += item_str + sep
            
    if len(current_line.strip()) > 0:
        out_lines.append(current_line.rstrip())
        
    comma = "" if loc == locales[-1] else ","
    out_lines.append(f"  }}{comma}")

out_lines.append("};")
out_lines.append("")
out_lines.append("if (typeof window !== 'undefined') {")
out_lines.append("  window.I18N_CATALOG = I18N_CATALOG;")
out_lines.append("}")
out_lines.append("")

content = "\n".join(out_lines)
print(f"Total lines: {len(out_lines)}")

# Test with parse_catalog_dict regex:
ALL_9_LOCALES = ["vi", "en", "zh", "ja", "ko", "th", "de", "ru", "es"]
cat = {l: {} for l in ALL_9_LOCALES}
for loc in ALL_9_LOCALES:
    m = re.search(rf"\b{loc}\s*:\s*\{{([^}}]+)\}}", content)
    if m:
        for k, _, v in re.findall(r"([a-zA-Z0-9_]+)\s*:\s*([\"`'])(.*?)\2", m.group(1)):
            cat[loc][k] = v

counts = {l: len(cat[l]) for l in ALL_9_LOCALES}
print("E2E Regex parsed counts:", counts)
assert all(c == 143 for c in counts.values()), "All locales must have 143 keys via E2E regex!"

catalog_path = Path("c:/Projects/FreeExile/client/webapp/js/data/i18n_catalog.js")
catalog_path.write_text(content, encoding="utf-8")
print("Written successfully to i18n_catalog.js!")
