"""Internationalization (i18n) support for OpenClaw dashboard.

Provides multi-language support with Chinese (zh) as default and English (en) as secondary.
Designed for easy extension to additional languages.
"""

from __future__ import annotations

from enum import Enum
from typing import Any, Dict, Optional


class Language(str, Enum):
    """Supported languages."""

    CHINESE = "zh"
    ENGLISH = "en"


class I18n:
    """Internationalization manager for dashboard translations.

    Supports language switching and nested key lookups.
    Default language is Chinese (zh).

    Example:
        >>> i18n = I18n()
        >>> i18n.t("status.agent_bankrupt")
        '代理破产'
        >>> i18n.set_language("en")
        >>> i18n.t("status.agent_bankrupt")
        'Agent Bankrupt'
    """

    # Translation dictionary
    _translations: Dict[str, Dict[str, Any]] = {
        "zh": {
            # Status messages
            "status": {
                "agent_bankrupt": "代理破产",
                "large_loss_detected": "检测到重大损失",
                "config_saved": "配置已保存",
                "config_loaded": "配置已加载",
                "config_error": "配置错误",
                "loading_config": "正在加载配置...",
                "saving_config": "正在保存配置...",
                "confirm": "已确认",
                "not_found": "未找到",
                "save_failed": "保存失败",
                "load_failed": "加载失败",
                " realtime": "实时",
                "disconnected": "已断开",
                "connecting": "连接中...",
            },
            # Navigation
            "nav": {
                "dashboard": "仪表盘",
                "config": "配置",
                "overview": "总览",
            },
            # Metrics
            "metrics": {
                "system_equity": "系统权益",
                "total_pnl": "总盈亏",
                "active_agents": "活跃 Agent",
                "total_trades": "总交易数",
                "avg_win_rate": "平均胜率",
                "trade_volume": "成交量",
                "bankrupt_agents": "破产",
            },
            # Charts
            "charts": {
                "equity_curve": "权益曲线",
                "pnl_distribution": "盈亏分布",
                "total_assets": "总资产",
                "profit": "盈利",
                "loss": "亏损",
            },
            # Agent status
            "agent": {
                "status": "状态",
                "balance": "余额",
                "win_rate": "胜率",
                "trades": "交易数",
                "thriving": "🚀 繁荣",
                "stable": "💪 稳定",
                "struggling": "⚠️ 困难",
                "critical": "🔴 危急",
                "bankrupt": "💀 破产",
                "activity_trade": "交易",
                "activity_analyze": "分析",
                "activity_rest": "休息",
            },
            # Trades
            "trade": {
                "recent_trades": "最近交易",
                "time": "时间",
                "symbol": "交易对",
                "side": "方向",
                "buy": "买入",
                "sell": "卖出",
                "pnl": "盈亏",
                "agent": "Agent",
            },
            # Alerts
            "alert": {
                "title": "警报",
                "bankruptcy_title": "代理破产",
                "bankruptcy_msg": "代理 {agent_id} 已破产！",
                "large_loss_title": "检测到重大损失",
                "large_loss_msg": "代理 {agent_id} 遭受重大损失: ${pnl:.2f}",
                "critical": "严重",
                "error": "错误",
                "warning": "警告",
                "info": "信息",
            },
            # Config page
            "config": {
                "title": "配置管理",
                "subtitle": "管理系统设置、成本、阈值和 LLM 提供商配置。",
                "save": "保存配置",
                "reset": "重置",
                "reload": "重新加载",
                "saving": "保存中...",
                "initial_capital": "初始资金",
                "cost_structure": "成本结构",
                "thresholds": "生存阈值",
                "simulation": "模拟设置",
                "llm_providers": "LLM 提供商",
            },
            # WebSocket messages
            "ws": {
                "status_update": "状态更新",
                "initial_state": "初始状态",
                "agent_update": "代理更新",
                "trade_update": "交易更新",
                "alert": "警报",
            },
        },
        "en": {
            # Status messages
            "status": {
                "agent_bankrupt": "Agent Bankrupt",
                "large_loss_detected": "Large Loss Detected",
                "config_saved": "Configuration Saved",
                "config_loaded": "Configuration Loaded",
                "config_error": "Configuration Error",
                "loading_config": "Loading Configuration...",
                "saving_config": "Saving Configuration...",
                "confirm": "Confirmed",
                "not_found": "Not Found",
                "save_failed": "Save Failed",
                "load_failed": "Load Failed",
                "realtime": "Realtime",
                "disconnected": "Disconnected",
                "connecting": "Connecting...",
            },
            # Navigation
            "nav": {
                "dashboard": "Dashboard",
                "config": "Configuration",
                "overview": "Overview",
            },
            # Metrics
            "metrics": {
                "system_equity": "System Equity",
                "total_pnl": "Total P&L",
                "active_agents": "Active Agents",
                "total_trades": "Total Trades",
                "avg_win_rate": "Avg Win Rate",
                "trade_volume": "Volume",
                "bankrupt_agents": "Bankrupt",
            },
            # Charts
            "charts": {
                "equity_curve": "Equity Curve",
                "pnl_distribution": "P&L Distribution",
                "total_assets": "Total Assets",
                "profit": "Profit",
                "loss": "Loss",
            },
            # Agent status
            "agent": {
                "status": "Status",
                "balance": "Balance",
                "win_rate": "Win Rate",
                "trades": "Trades",
                "thriving": "🚀 Thriving",
                "stable": "💪 Stable",
                "struggling": "⚠️ Struggling",
                "critical": "🔴 Critical",
                "bankrupt": "💀 Bankrupt",
                "activity_trade": "TRADE",
                "activity_analyze": "ANALYZE",
                "activity_rest": "REST",
            },
            # Trades
            "trade": {
                "recent_trades": "Recent Trades",
                "time": "Time",
                "symbol": "Symbol",
                "side": "Side",
                "buy": "BUY",
                "sell": "SELL",
                "pnl": "P&L",
                "agent": "Agent",
            },
            # Alerts
            "alert": {
                "title": "Alert",
                "bankruptcy_title": "Agent Bankrupt",
                "bankruptcy_msg": "Agent {agent_id} has gone bankrupt!",
                "large_loss_title": "Large Loss Detected",
                "large_loss_msg": "Agent {agent_id} suffered large loss: ${pnl:.2f}",
                "critical": "Critical",
                "error": "Error",
                "warning": "Warning",
                "info": "Info",
            },
            # Config page
            "config": {
                "title": "Configuration Management",
                "subtitle": "Manage system settings, costs, thresholds, and LLM provider configuration.",
                "save": "Save Configuration",
                "reset": "Reset",
                "reload": "Reload",
                "saving": "Saving...",
                "initial_capital": "Initial Capital",
                "cost_structure": "Cost Structure",
                "thresholds": "Survival Thresholds",
                "simulation": "Simulation Settings",
                "llm_providers": "LLM Providers",
            },
            # WebSocket messages
            "ws": {
                "status_update": "Status Update",
                "initial_state": "Initial State",
                "agent_update": "Agent Update",
                "trade_update": "Trade Update",
                "alert": "Alert",
            },
        },
    }

    def __init__(self, language: str = "zh") -> None:
        """Initialize i18n with specified language.

        Args:
            language: Language code ('zh' for Chinese, 'en' for English)
        """
        self._language = language if language in self._translations else "zh"
        self._fallback = "zh"

    def set_language(self, language: str) -> None:
        """Change current language.

        Args:
            language: Language code ('zh' or 'en')

        Raises:
            ValueError: If language is not supported
        """
        if language not in self._translations:
            raise ValueError(f"Unsupported language: {language}. Supported: {list(self._translations.keys())}")
        self._language = language

    def get_language(self) -> str:
        """Get current language code."""
        return self._language

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

        Supports nested keys using dot notation (e.g., 'status.agent_bankrupt').
        Supports string interpolation with keyword arguments.

        Args:
            key: Translation key (e.g., 'status.agent_bankrupt')
            **kwargs: Values for string interpolation

        Returns:
            Translated string

        Example:
            >>> i18n = I18n("zh")
            >>> i18n.t("alert.bankruptcy_msg", agent_id="bull_001")
            '代理 bull_001 已破产！'
        """
        # Get translation
        result = self._get_nested_key(self._translations[self._language], key)

        # Fallback if not found
        if result is None and self._language != self._fallback:
            result = self._get_nested_key(self._translations[self._fallback], key)

        # Return key if translation not found
        if result is None:
            return key

        # Format with kwargs if provided
        if kwargs:
            try:
                return result.format(**kwargs)
            except (KeyError, ValueError):
                return result

        return result

    def _get_nested_key(self, data: Dict[str, Any], key: str) -> Optional[str]:
        """Get value from nested dictionary using dot notation.

        Args:
            data: Dictionary to search
            key: Dot-separated key path

        Returns:
            Value if found, None otherwise
        """
        keys = key.split(".")
        current = data

        for k in keys:
            if isinstance(current, dict) and k in current:
                current = current[k]
            else:
                return None

        return str(current) if current is not None else None

    def get_available_languages(self) -> Dict[str, str]:
        """Get list of available languages.

        Returns:
            Dictionary mapping language codes to display names
        """
        return {
            "zh": "中文",
            "en": "English",
        }

    def add_translation(self, language: str, key: str, value: str) -> None:
        """Add or update a translation.

        Args:
            language: Language code
            key: Dot-separated key path
            value: Translation value

        Raises:
            ValueError: If language is not supported
        """
        if language not in self._translations:
            raise ValueError(f"Unsupported language: {language}")

        keys = key.split(".")
        current = self._translations[language]

        # Navigate/create nested structure
        for k in keys[:-1]:
            if k not in current:
                current[k] = {}
            current = current[k]

        current[keys[-1]] = value

    def get_all_translations(self, language: Optional[str] = None) -> Dict[str, Any]:
        """Get all translations for a language.

        Args:
            language: Language code (defaults to current language)

        Returns:
            Complete translation dictionary
        """
        lang = language or self._language
        return self._translations.get(lang, {}).copy()


# Global i18n instance for convenience
_default_i18n = I18n()


def t(key: str, **kwargs: Any) -> str:
    """Global translate function using default i18n instance.

    Args:
        key: Translation key
        **kwargs: Values for string interpolation

    Returns:
        Translated string
    """
    return _default_i18n.t(key, **kwargs)


def set_language(language: str) -> None:
    """Set language for global i18n instance.

    Args:
        language: Language code ('zh' or 'en')
    """
    _default_i18n.set_language(language)


def get_language() -> str:
    """Get current language of global i18n instance."""
    return _default_i18n.get_language()
