"""工具模式定义通用工具函数

这个文件包含了所有工具模式定义文件中的通用函数和工具。
"""

from typing import Dict, Any, Optional
from vita.config import DEFAULT_LANGUAGE

# 全局工具描述注册表
TOOL_DESCRIPTIONS_REGISTRY: Dict[str, Dict[str, Any]] = {}

def register_tool_descriptions(domain: str, descriptions: Dict[str, Dict[str, Any]]):
    """为特定领域注册工具描述
    
    Args:
        domain: 领域名称 (例如: 'delivery', 'instore', 'ota', 'toolkit')
        descriptions: 工具名称到描述的映射字典
    """
    TOOL_DESCRIPTIONS_REGISTRY[domain] = descriptions

def get_tool_description(domain: str, tool_name: str) -> Optional[Dict[str, Any]]:
    """从注册表中获取工具描述
    
    Args:
        domain: 领域名称
        tool_name: 工具名称
        
    Returns:
        工具描述字典，如果未找到则返回None
    """
    domain_descriptions = TOOL_DESCRIPTIONS_REGISTRY.get(domain, {})
    return domain_descriptions.get(tool_name)

def generate_tool_docstring(domain: str, tool_name: str) -> str:
    """通过组合所有信息为工具生成完整的文档字符串
    
    Args:
        domain: 领域名称
        tool_name: 工具名称
        
    Returns:
        完整格式化的文档字符串
    """
    tool_desc = get_tool_description(domain, tool_name)
    if not tool_desc:
        return ""
    
    # 构建文档字符串
    docstring_parts = []
    
    # 描述
    docstring_parts.append(tool_desc['description'])
    
    # 前置条件
    docstring_parts.append("Preconditions:")
    docstring_parts.append(f"    - {tool_desc['preconditions']}")
    
    # 后置条件
    docstring_parts.append("Postconditions:")
    docstring_parts.append(f"    - {tool_desc['postconditions']}")
    
    # 参数
    docstring_parts.append("")
    docstring_parts.append("Args:")
    for arg_name, arg_desc in tool_desc['args'].items():
        docstring_parts.append(f"    {arg_name}: {arg_desc}")
    
    # 返回值
    docstring_parts.append("")
    docstring_parts.append("Returns:")
    docstring_parts.append(f"    {tool_desc['returns']}")
    
    return "\n".join(docstring_parts)

def get_domain_from_class(cls) -> Optional[str]:
    """从类名或模块路径中提取领域名称
    
    Args:
        cls: 类对象
        
    Returns:
        领域名称，如果无法确定则返回None
    """
    # 尝试从类名中提取领域
    class_name = cls.__name__.lower()
    
    # 常见领域模式
    if 'delivery' in class_name:
        return 'delivery'
    elif 'instore' in class_name:
        return 'instore'
    elif 'ota' in class_name:
        return 'ota'
    elif 'toolkitbase' in class_name or 'generictoolkit' in class_name:
        return 'toolkit'
    
    # 尝试从模块路径中提取
    module_name = cls.__module__.lower()
    if 'delivery' in module_name:
        return 'delivery'
    elif 'instore' in module_name:
        return 'instore'
    elif 'ota' in module_name:
        return 'ota'
    elif 'toolkit' in module_name:
        return 'toolkit'
    
    return None

# 通用工具描述管理类
class ToolSchemaManager:
    """工具模式管理器，提供通用的工具描述管理功能"""
    
    def __init__(self, domain: str, descriptions_zh: Dict[str, Dict[str, Any]], 
                 descriptions_en: Dict[str, Dict[str, Any]]):
        """初始化工具模式管理器
        
        Args:
            domain: 领域名称
            descriptions_zh: 中文工具描述
            descriptions_en: 英文工具描述
        """
        self.domain = domain
        self.descriptions_zh = descriptions_zh
        self.descriptions_en = descriptions_en
        self.language_config = DEFAULT_LANGUAGE
        
        # 工具类型映射
        self.tool_type_mapping = {
            "GENERIC": "通用工具" if self.language_config == 'chinese' else "Generic Tool",
            "READ": "读取工具" if self.language_config == 'chinese' else "Read Tool",
            "WRITE": "写入工具" if self.language_config == 'chinese' else "Write Tool"
        }
        
        # 自动注册到全局注册表
        self._register_with_global_registry()
    
    def get_tool_descriptions(self) -> Dict[str, Dict[str, Any]]:
        """根据语言配置获取工具描述"""
        if self.language_config == 'english':
            return self.descriptions_en
        else:
            return self.descriptions_zh
    
    def get_tool_description(self, tool_name: str) -> Dict[str, Any]:
        """根据名称获取特定工具的描述
        
        Args:
            tool_name: 工具名称
            
        Returns:
            包含工具描述、前置条件、后置条件、参数、返回值和工具类型的字典
        """
        return self.get_tool_descriptions().get(tool_name, {})
    
    def get_all_tool_names(self) -> list:
        """获取所有可用工具名称的列表
        
        Returns:
            工具名称列表
        """
        return list(self.get_tool_descriptions().keys())
    
    def get_tools_by_type(self, tool_type: str) -> Dict[str, Dict[str, Any]]:
        """获取特定类型的所有工具
        
        Args:
            tool_type: 工具类型 (GENERIC, READ, 或 WRITE)
            
        Returns:
            工具名称到描述的映射字典
        """
        return {
            name: desc for name, desc in self.get_tool_descriptions().items() 
            if desc["tool_type"] == tool_type
        }
    
    def get_tool_count_by_type(self) -> Dict[str, int]:
        """按类型获取工具数量
        
        Returns:
            工具类型到数量的映射字典
        """
        counts = {}
        for desc in self.get_tool_descriptions().values():
            tool_type = desc["tool_type"]
            counts[tool_type] = counts.get(tool_type, 0) + 1
        return counts
    
    def get_tool_args(self, tool_name: str) -> Dict[str, str]:
        """根据名称获取特定工具的参数
        
        Args:
            tool_name: 工具名称
            
        Returns:
            参数名称到描述的映射字典
        """
        tool_desc = self.get_tool_descriptions().get(tool_name, {})
        return tool_desc.get("args", {})
    
    def get_tool_returns(self, tool_name: str) -> str:
        """根据名称获取特定工具的返回值描述
        
        Args:
            tool_name: 工具名称
            
        Returns:
            描述工具返回内容的字符串
        """
        tool_desc = self.get_tool_descriptions().get(tool_name, {})
        return tool_desc.get("returns", "")
    
    def _register_with_global_registry(self):
        """将工具描述注册到全局工具包注册表"""
        try:
            register_tool_descriptions(self.domain, self.get_tool_descriptions())
        except ImportError:
            # 如果toolkit_schema不可用，跳过注册
            pass

# 便捷函数，用于创建和管理工具模式
def create_tool_schema_manager(domain: str, descriptions_zh: Dict[str, Dict[str, Any]], 
                              descriptions_en: Dict[str, Dict[str, Any]]) -> ToolSchemaManager:
    """创建工具模式管理器的便捷函数
    
    Args:
        domain: 领域名称
        descriptions_zh: 中文工具描述
        descriptions_en: 英文工具描述
        
    Returns:
        工具模式管理器实例
    """
    return ToolSchemaManager(domain, descriptions_zh, descriptions_en)

# 通用工具类型映射
def get_tool_type_mapping() -> Dict[str, str]:
    """获取工具类型映射
    
    Returns:
        工具类型到本地化名称的映射
    """
    language_config = DEFAULT_LANGUAGE
    return {
        "GENERIC": "通用工具" if language_config == 'chinese' else "Generic Tool",
        "READ": "读取工具" if language_config == 'chinese' else "Read Tool",
        "WRITE": "写入工具" if language_config == 'chinese' else "Write Tool"
    }