#!/usr/bin/env python3
"""
Compile .po files to .mo for Chess Podium.
Uses polib if available, otherwise falls back to subprocess php.
Run: py compile-mo.py   or   python compile-mo.py
"""
import subprocess
import sys
from pathlib import Path

SCRIPT_DIR = Path(__file__).parent
PLUGIN_DIR = SCRIPT_DIR.parent

def compile_with_polib():
    """Compile using polib (pip install polib)."""
    try:
        import polib
    except ImportError:
        return False
    compiled = 0
    for po_file in SCRIPT_DIR.glob("*.po"):
        mo_file = po_file.with_suffix(".mo")
        try:
            po = polib.pofile(str(po_file))
            po.save_as_mofile(fpath=str(mo_file))
            print(f"Compiled: {po_file.name} -> {mo_file.name}")
            compiled += 1
        except Exception as e:
            print(f"Failed {po_file.name}: {e}")
    return compiled > 0

def compile_with_php():
    """Compile using PHP script."""
    php_script = PLUGIN_DIR / "compile-languages.php"
    if not php_script.exists():
        return False
    for cmd in ["php", "php8", "php7"]:
        try:
            result = subprocess.run(
                [cmd, str(php_script)],
                cwd=str(PLUGIN_DIR),
                capture_output=True,
                text=True,
                timeout=30,
            )
            if result.returncode == 0:
                print(result.stdout)
                return True
        except (FileNotFoundError, subprocess.TimeoutExpired):
            continue
    return False

def main():
    if compile_with_polib():
        print("\nDone.")
        return 0
    print("polib not found. Try: pip install polib")
    print("Attempting PHP fallback...")
    if compile_with_php():
        return 0
    print("PHP not found. Install polib (pip install polib) or PHP to compile.")
    return 1

if __name__ == "__main__":
    sys.exit(main())
