# 中文注释：
# 文件：echobot/agent/tools/call_agent.py
# 说明：Agent 间调用工具。

"""Call Agent Tool - Agent 间调用"""

from typing import Any

from echobot.agent.tools.base import Tool


class CallAgentTool(Tool):
    """
    Agent 间调用工具

    允许当前 Agent 调用其他 Agent 来完成任务。
    """

    def __init__(
        self,
        call_agent_callback,
        get_available_agents_callback,
        current_agent_id: str,
    ):
        """
        Initialize CallAgentTool.

        Args:
            call_agent_callback: 调用 Agent 的回调函数 (caller_id, target_id, task, context) -> str
            get_available_agents_callback: 获取可用 Agent 列表的回调
            current_agent_id: 当前 Agent 的 ID
        """
        self._call_agent = call_agent_callback
        self._get_available_agents = get_available_agents_callback
        self._current_agent_id = current_agent_id

    @property
    def name(self) -> str:
        return "call_agent"

    @property
    def description(self) -> str:
        return "Call another agent to help with the task. Use this when you need assistance from a specialized agent."

    @property
    def parameters(self) -> dict[str, Any]:
        return {
            "type": "object",
            "properties": {
                "agent_id": {
                    "type": "string",
                    "description": "Target agent ID to call (e.g., 'coder', 'reviewer', 'tester')",
                },
                "task": {
                    "type": "string",
                    "description": "Task description for the target agent to execute",
                },
                "context": {
                    "type": "object",
                    "description": "Optional context information to pass to the target agent",
                },
            },
            "required": ["agent_id", "task"],
        }

    async def execute(self, agent_id: str, task: str, context: dict | None = None, **kwargs) -> str:
        """Execute agent-to-agent call."""
        if self._call_agent is None:
            return "Error: Agent collaboration is not configured"

        try:
            result = await self._call_agent(
                caller_id=self._current_agent_id,
                target_agent_id=agent_id,
                task=task,
                context=context,
            )
            return result
        except Exception as e:
            return f"Error calling agent '{agent_id}': {str(e)}"


class ListAgentsTool(Tool):
    """
    列出可用 Agent 工具

    列出当前可以调用的其他 Agent。
    """

    def __init__(self, get_available_agents_callback):
        """
        Initialize ListAgentsTool.

        Args:
            get_available_agents_callback: 获取可用 Agent 列表的回调
        """
        self._get_available_agents = get_available_agents_callback

    @property
    def name(self) -> str:
        return "list_agents"

    @property
    def description(self) -> str:
        return "List all available agents that can be called for assistance."

    @property
    def parameters(self) -> dict[str, Any]:
        return {
            "type": "object",
            "properties": {},
        }

    async def execute(self, **kwargs) -> str:
        """Execute list agents."""
        if self._get_available_agents is None:
            return "Error: Agent collaboration is not configured"

        try:
            agents = self._get_available_agents()
            if not agents:
                return "No available agents to call."

            lines = ["Available agents:"]
            for agent in agents:
                lines.append(f"- {agent['id']}: {agent['name']} (role: {agent['role']})")

            return "\n".join(lines)
        except Exception as e:
            return f"Error listing agents: {str(e)}"
