"""
Agent 核心管理器
"""
import os
from typing import Any, Optional

from app.agent.core.executor import AgentExecutor
from app.agent.memory.session import SessionManager
from app.agent.tools.registry import ToolRegistry
from app.llm.factory import LLMFactory
from app.security.audit import AuditLogger


class AgentManager:
    """Agent 管理器 - 负责加载和管理所有 Agent"""

    def __init__(
        self,
        llm_provider: str = "openai",
        openai_api_key: Optional[str] = None,
        anthropic_api_key: Optional[str] = None,
    ):
        self.llm_provider = llm_provider
        self.openai_api_key = openai_api_key or os.getenv("OPENAI_API_KEY")
        self.anthropic_api_key = anthropic_api_key or os.getenv("ANTHROPIC_API_KEY")

        # 初始化组件
        self.llm_factory = LLMFactory(
            provider=llm_provider,
            openai_api_key=self.openai_api_key,
            anthropic_api_key=self.anthropic_api_key
        )
        self.tool_registry = ToolRegistry()
        self.session_manager = SessionManager()
        self.audit_logger = AuditLogger()

        # 已加载的 Agent
        self.agents: dict[str, dict] = {}
        self.executors: dict[str, AgentExecutor] = {}

        # 注册默认工具
        self._register_default_tools()

    def _register_default_tools(self):
        """注册默认工具"""
        from app.agent.tools.impl import search, calculator, time_tool
        from app.agent.tools.impl import sandbox, database, api_client

        # 安全工具 - Safe 级别
        self.tool_registry.register(
            name="search",
            func=search.search_web,
            description="Search the web for information",
            security_level="safe"
        )

        self.tool_registry.register(
            name="calculator",
            func=calculator.calculate,
            description="Perform mathematical calculations",
            security_level="safe"
        )

        self.tool_registry.register(
            name="get_current_time",
            func=time_tool.get_current_time,
            description="Get current date and time",
            security_level="safe"
        )

        # 需要审核的工具 - Review 级别
        self.tool_registry.register(
            name="execute_code",
            func=sandbox.sandbox.execute,
            description="Execute code in sandbox (Python/JavaScript)",
            security_level="review",
            require_approval=True,
            parameters={
                "type": "object",
                "properties": {
                    "code": {"type": "string", "description": "Code to execute"},
                    "language": {"type": "string", "default": "python"},
                    "timeout": {"type": "integer", "default": 30}
                },
                "required": ["code"]
            }
        )

        self.tool_registry.register(
            name="query_database",
            func=database.query_data,
            description="Query database (SELECT only)",
            security_level="review",
            require_approval=True,
            parameters={
                "type": "object",
                "properties": {
                    "sql": {"type": "string", "description": "SELECT query"}
                },
                "required": ["sql"]
            }
        )

        self.tool_registry.register(
            name="call_api",
            func=api_client.call_api,
            description="Call external API (whitelist only)",
            security_level="review",
            require_approval=True,
            parameters={
                "type": "object",
                "properties": {
                    "api_name": {"type": "string"},
                    "endpoint": {"type": "string"},
                    "params": {"type": "object"}
                },
                "required": ["api_name"]
            }
        )

    async def load_agents(self):
        """加载 Agent 配置"""
        # TODO: 从数据库或配置文件加载
        # 这里先注册一些示例 Agent

        self.agents["assistant"] = {
            "name": "General Assistant",
            "description": "A general purpose assistant",
            "system_prompt": "You are a helpful assistant.",
            "tools": ["search", "calculator", "get_current_time"]
        }

        self.agents["coder"] = {
            "name": "Code Assistant",
            "description": "Helps with coding tasks",
            "system_prompt": "You are a helpful coding assistant. You can write, explain, and debug code.",
            "tools": ["search", "calculator"]
        }

        # 为每个 Agent 创建执行器
        for agent_id, config in self.agents.items():
            self.executors[agent_id] = AgentExecutor(
                agent_id=agent_id,
                llm_factory=self.llm_factory,
                tool_registry=self.tool_registry,
                session_manager=self.session_manager,
                audit_logger=self.audit_logger,
                config=config
            )

    async def execute(
        self,
        agent_id: str,
        message: str,
        session_id: str,
        context: dict = None
    ) -> dict[str, Any]:
        """执行 Agent"""
        if agent_id not in self.executors:
            raise ValueError(f"Agent '{agent_id}' not found")

        executor = self.executors[agent_id]

        # 执行
        result = await executor.run(
            message=message,
            session_id=session_id,
            context=context or {}
        )

        return result

    def list_tools(self) -> list:
        """列出所有可用工具"""
        return self.tool_registry.list_tools()

    def list_agents(self) -> list[dict]:
        """列出所有 Agent"""
        return [
            {
                "id": agent_id,
                "name": config["name"],
                "description": config["description"]
            }
            for agent_id, config in self.agents.items()
        ]

    def get_agent_info(self, agent_id: str) -> Optional[dict]:
        """获取 Agent 信息"""
        if agent_id not in self.agents:
            return None
        return self.agents[agent_id]
