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

locales = ['vi', 'en', 'zh', 'ja', 'ko', 'th', 'de', 'ru', 'es']
cat = {l: {} for l in locales}

with open('docs/standards/GLOBAL_LOCALIZATION_DICTIONARY.md', encoding='utf-8') as f:
    in_sec13 = False
    for line in f:
        if '## 13.' in line:
            in_sec13 = True
            continue
        if in_sec13 and line.startswith('## '):
            break
        if in_sec13 and line.startswith('|') and not line.startswith('| :---') and not line.startswith('| Khóa Key'):
            parts = [p.strip() for p in line.strip().split('|')[1:-1]]
            if len(parts) >= 10:
                k = parts[0]
                for idx, loc in enumerate(locales):
                    cat[loc][k] = parts[idx + 1]

channels = ['world', 'zone', 'guild', 'party', 'whisper', 'system', 'recruit', 'feedback']
channel_i18n = {}
for loc in locales:
    channel_i18n[loc] = {c: cat[loc][f'channel_{c}'] for c in channels}

out = []
out.append('// =============================================================================')
out.append('// FREEEXILE: 9-LANGUAGE CHAT LOCALIZATION CATALOG')
out.append('// Module: chat_i18n_catalog.js')
out.append('// 100% key parity across vi, en, zh, ja, ko, th, de, ru, es (77 keys per locale)')
out.append('// =============================================================================')
out.append('')
out.append('export const CHANNEL_I18N = {')
for loc in locales:
    ch_items = [f'"{c}": {json.dumps(channel_i18n[loc][c], ensure_ascii=False)}' for c in channels]
    out.append(f'  {loc}: {{ {", ".join(ch_items)} }},')
out.append('};')
out.append('')
out.append('export const CHAT_I18N_CATALOG = {')
for loc in locales:
    out.append(f'  {loc}: {{')
    keys = list(cat[loc].keys())
    for i in range(0, len(keys), 2):
        chunk = keys[i:i+2]
        line_parts = [f'"{k}": {json.dumps(cat[loc][k], ensure_ascii=False)}' for k in chunk]
        sep = ',' if i + 2 < len(keys) else (',' if loc != locales[-1] else '')
        out.append(f'    {", ".join(line_parts)}{sep}')
    out.append('  },' if loc != locales[-1] else '  }')
out.append('};')
out.append('')
out.append('if (typeof window !== "undefined") {')
out.append('  window.CHANNEL_I18N = CHANNEL_I18N;')
out.append('  window.CHAT_I18N_CATALOG = CHAT_I18N_CATALOG;')
out.append('}')
out.append('')

content = '\n'.join(out)
with open('client/webapp/js/data/chat_i18n_catalog.js', 'w', encoding='utf-8') as f:
    f.write(content)

print(f'Generated chat_i18n_catalog.js with {len(out)} lines.')
