"""
Generate per-locale index.ts files that merge all namespace JSON files.

Creates:
  frontend/src/lib/i18n/messages/<locale>/index.ts
"""

import json
from pathlib import Path
from collections import defaultdict

ROOT = Path(__file__).parent.parent
MESSAGES_DIR = ROOT / "frontend" / "src" / "lib" / "i18n" / "messages"

manifest = json.loads((MESSAGES_DIR / "index.json").read_text(encoding="utf-8"))

for locale in manifest["locales"]:
    locale_dir = MESSAGES_DIR / locale
    namespaces = sorted(p.stem for p in locale_dir.glob("*.json"))

    imports = "\n".join(f'import {ns} from "./{ns}.json";'
                        for ns in namespaces)
    export_obj = "\n  ".join(f"...{ns}," for ns in namespaces)

    index_ts = f'''// Auto-generated by scripts/generate_i18n_index.py
// Merges all namespace JSON files for locale "{locale}".

{imports}

const messages: Record<string, string> = {{
  {export_obj}
}};

export default messages;
'''

    (locale_dir / "index.ts").write_text(index_ts, encoding="utf-8")

print(f"Generated index.ts for {len(manifest['locales'])} locales")
