"""Internationalization support for IEUM.

Provides translation utilities for user-facing strings across TUI, WebUI,
and VSCode extension platforms.

Supported locales:
    - en: English
    - ko: Korean (default)

Configuration:
    Set the IEUM_LANG environment variable to change the locale:
        IEUM_LANG=en  -> English
        IEUM_LANG=ko  -> Korean
"""

from __future__ import annotations

import json
import os
from pathlib import Path
from typing import Any


_DEFAULT_LOCALE = "en"
_CURRENT_LOCALE = os.environ.get("IEUM_LANG", "en")
_translations: dict[str, dict[str, str]] = {}


def set_locale(locale: str) -> None:
    """Set the current locale.

    Args:
        locale: Locale code ('en' or 'ko')
    """
    global _CURRENT_LOCALE
    if locale not in ("en", "ko"):
        locale = _DEFAULT_LOCALE
    _CURRENT_LOCALE = locale
    _load_translations()


def get_locale() -> str:
    """Get the current locale code.

    Returns:
        Current locale code ('en' or 'ko')
    """
    return _CURRENT_LOCALE


def get_supported_locales() -> list[str]:
    """Get list of supported locale codes.

    Returns:
        List of supported locale codes
    """
    return ["en", "ko"]


def t(key: str, **kwargs: Any) -> str:
    """Translate a key to the current locale.

    Falls back to the default locale (English) if the key is not found
    in the current locale. Returns the raw key if not found in any locale.

    Supports {placeholder} formatting via keyword arguments.

    Args:
        key: Translation key (e.g., 'welcome.title')
        **kwargs: Placeholder values for string formatting

    Returns:
        Translated string with placeholders resolved
    """
    locale_dict = _translations.get(_CURRENT_LOCALE, {})
    text = locale_dict.get(key) or _translations.get(_DEFAULT_LOCALE, {}).get(key, key)
    if kwargs:
        try:
            text = text.format(**kwargs)
        except (KeyError, IndexError):
            pass
    return text


def get_translations_dict(locale: str | None = None) -> dict[str, str]:
    """Get the full translations dictionary for a locale.

    Useful for embedding translations in WebUI templates or VSCode webviews.

    Args:
        locale: Locale code. Defaults to current locale.

    Returns:
        Dictionary mapping translation keys to translated strings
    """
    locale = locale or _CURRENT_LOCALE
    return dict(_translations.get(locale, {}))


def _load_translations() -> None:
    """Load all translation files from the locales directory."""
    global _translations
    locale_dir = Path(__file__).parent / "locales"
    if not locale_dir.exists():
        return
    for locale_file in locale_dir.glob("*.json"):
        locale = locale_file.stem
        with open(locale_file, encoding="utf-8") as f:
            _translations[locale] = json.load(f)


# Load translations on import
_load_translations()
