"""
Language Manager — multi-language support for GoldAutoTrade.

Supports: zh-CN, en, ja, ko, ar
Fallback chain: requested → zh-CN (default) → key itself

Usage:
    from src.i18n import translate, get_lang_manager
    msg = translate("strategy.status.running", lang="en")
"""

from __future__ import annotations

import json
import os
from pathlib import Path
from typing import Dict, Optional

SUPPORTED_LANGUAGES = {
    "zh-CN": {"name": "简体中文", "name_en": "Simplified Chinese", "dir": "ltr"},
    "en":    {"name": "English", "name_en": "English", "dir": "ltr"},
    "ja":    {"name": "日本語", "name_en": "Japanese", "dir": "ltr"},
    "ko":    {"name": "한국어", "name_en": "Korean", "dir": "ltr"},
    "ar":    {"name": "العربية", "name_en": "Arabic", "dir": "rtl"},
}

DEFAULT_LANG = "zh-CN"


class LangManager:
    """Loads and caches language resource files. Provides key-based translation."""

    def __init__(self, locales_dir: Optional[Path] = None):
        self._cache: Dict[str, dict] = {}
        self._locales_dir = locales_dir or self._default_locales_dir()
        self._current_lang = os.environ.get("GAT_LANG", DEFAULT_LANG)

    @staticmethod
    @staticmethod
    def _default_locales_dir() -> Path:
        # Priority: package directory (shipped with code) → app data (user overrides)
        pkg_dir = Path(__file__).parent / "locales"
        if pkg_dir.exists():
            return pkg_dir
        try:
            from config_manager import get_app_dir
            return get_app_dir() / "locales"
        except Exception:
            return pkg_dir

    def load(self, lang: str) -> dict:
        """Load a language pack, caching it in memory."""
        if lang in self._cache:
            return self._cache[lang]

        file_path = self._locales_dir / f"{lang}.json"
        if not file_path.exists():
            return {}

        try:
            data = json.loads(file_path.read_text(encoding="utf-8"))
            flat = self._flatten(data)
            self._cache[lang] = flat
            return flat
        except Exception:
            return {}

    @staticmethod
    def _flatten(nested: dict, prefix: str = "") -> dict:
        """Flatten nested JSON keys with dot notation."""
        result = {}
        for k, v in nested.items():
            full_key = f"{prefix}.{k}" if prefix else k
            if isinstance(v, dict):
                result.update(LangManager._flatten(v, full_key))
            else:
                result[full_key] = str(v)
        return result

    def translate(self, key: str, lang: Optional[str] = None, **kwargs) -> str:
        """Translate a key to the specified language. Falls back to default."""
        lang = lang or self._current_lang
        # Try requested language
        pack = self.load(lang)
        if key in pack:
            return pack[key].format(**kwargs) if kwargs else pack[key]
        # Fallback to default
        if lang != DEFAULT_LANG:
            default_pack = self.load(DEFAULT_LANG)
            if key in default_pack:
                return default_pack[key].format(**kwargs) if kwargs else default_pack[key]
        # Last resort: return the key itself
        return key

    def set_language(self, lang: str) -> bool:
        """Set current language. Returns True if language is supported."""
        if lang in SUPPORTED_LANGUAGES:
            self._current_lang = lang
            return True
        return False

    @property
    def current_language(self) -> str:
        return self._current_lang

    def list_languages(self) -> dict:
        return SUPPORTED_LANGUAGES


# ── Singleton ──

_manager: Optional[LangManager] = None


def get_lang_manager() -> LangManager:
    global _manager
    if _manager is None:
        _manager = LangManager()
    return _manager


def translate(key: str, lang: Optional[str] = None, **kwargs) -> str:
    """Convenience function: translate a key to current or specified language."""
    return get_lang_manager().translate(key, lang=lang, **kwargs)
