#!/usr/bin/env python
"""
Compile .po files to .mo files without requiring GNU gettext tools.
Uses polib library which is pure Python.
"""

import os
import sys

try:
    import polib
except ImportError:
    print("Installing polib...")
    os.system(f"{sys.executable} -m pip install -q polib")
    import polib

def compile_po_to_mo(po_file, mo_file):
    """Compile a .po file to .mo file."""
    try:
        # Load and save (this compiles to binary .mo format)
        po = polib.pofile(po_file)
        po.save_as_mofile(mo_file)
        return True
    except Exception as e:
        print(f"Error compiling {po_file}: {e}")
        return False

def main():
    base_dir = os.path.dirname(os.path.abspath(__file__))
    locale_dir = os.path.join(base_dir, 'locale')

    languages = ['vi', 'en']
    compiled_count = 0

    for lang in languages:
        po_file = os.path.join(locale_dir, lang, 'LC_MESSAGES', 'django.po')
        mo_file = os.path.join(locale_dir, lang, 'LC_MESSAGES', 'django.mo')

        if os.path.exists(po_file):
            print(f"Compiling {lang}...", end=' ')
            if compile_po_to_mo(po_file, mo_file):
                size = os.path.getsize(mo_file)
                print(f"OK ({size:,} bytes)")
                compiled_count += 1
            else:
                print("FAILED")
        else:
            print(f"Skipping {lang} (no .po file)")

    if compiled_count > 0:
        print(f"\nSuccess! Compiled {compiled_count} language(s)")
        print("\nNow restart your Django server:")
        print("  python manage.py runserver")
        print("\nThen visit:")
        print("  http://127.0.0.1:8000/en/legal/privacy/")
        print("  http://127.0.0.1:8000/vi/legal/privacy/")
    else:
        print("\nNo languages compiled. Check locale directory.")
        sys.exit(1)

if __name__ == '__main__':
    main()
