import os
import sys
import yaml
from pathlib import Path

class LangManager:
    """简单的语言管理器"""
    
    def __init__(self):
        self.language = 'zh'
        self.translations = {}
        self.language_file_path = None
        # 初始化时尝试加载语言配置文件
        self._init_language_file()
        self._load_translations()
    
    def _init_language_file(self):
        """初始化语言文件路径"""
        # 查找可能的语言文件位置
        possible_paths = [
            # 相对于当前文件的位置
            Path(os.path.dirname(os.path.abspath(__file__))) / 'config' / 'language.yaml',
            # 相对于工作目录的位置
            Path('.') / 'config' / 'language.yaml',
            # 用户配置目录
            Path.home() / '.shortcutkey' / 'language.yaml'
        ]
        
        for path in possible_paths:
            if path.exists():
                self.language_file_path = path
                break
    
    def _load_translations(self):
        """从配置文件加载翻译"""
        if self.language_file_path and self.language_file_path.exists():
                with open(self.language_file_path, 'r', encoding='utf-8') as f:
                    self.translations = yaml.safe_load(f)
                if not isinstance(self.translations, dict):
                    self.translations = {}

    def set_language(self, lang):
        """设置语言"""
        if lang in self.translations:
            self.language = lang
    
    def get_text(self, key_path, **kwargs):
        """获取翻译文本"""
        keys = key_path.split('.')
        text = self.translations.get(self.language, {})
        for key in keys:
            if isinstance(text, dict) and key in text:
                text = text[key]
            else:
                return key_path
        
        if isinstance(text, str):
            try:
                return text.format(**kwargs)
            except (KeyError, IndexError):
                pass
        
        return text

# 全局实例
_lang_manager = LangManager()

def get_lang_manager():
    """获取语言管理器实例"""
    return _lang_manager

def _(key_path, **kwargs):
    """翻译函数，简化调用"""
    return _lang_manager.get_text(key_path, **kwargs)