"""
CrewAI 适配器：将 ACT 工具包装为 CrewAI Tool
"""

from typing import Any, Optional, Type
from pydantic import BaseModel

class ACTExecutionError(Exception):
    """ACT 执行异常，供 CrewAI 捕获"""
    pass

class ACTTool:
    """
    将 ACT Kernel 包装为 CrewAI 可调用的工具。
    每个 ACTTool 实例对应一个具体的工具（如 weather.get_current）。
    """
    name: str = ""
    description: str = ""
    args_schema: Optional[Type[BaseModel]] = None

    def __init__(self, kernel, tool_name: str, action: str, metadata: dict):
        super().__init__()
        self.kernel = kernel
        self.tool_name = tool_name
        self.action = action
        self.intent = f"{tool_name}.{action}"
        self.name = self.intent
        self.description = metadata.get("description", f"Tool {tool_name}/{action}")
        # 可以在此处根据 metadata 中的 parameters 动态生成 args_schema
        # 为简化，这里直接接受 **kwargs

    def _run(self, **kwargs) -> Any:
        """CrewAI 调用的入口"""
        result = self.kernel.dispatch(self.intent, kwargs)
        status = result["execution"]["status"]
        if status == "ok":
            return result["payload"]
        error_info = result.get("error", {"code": "unknown", "message": "Unknown error"})
        raise ACTExecutionError(f"ACT Error [{error_info['code']}]: {error_info['message']}")
