"""Router Agent 工具表管理工具

提供给 Router Agent 调用的工具表查询和管理功能。
"""

from typing import Any
from tool_agent.tool_table import get_client


def query_knowhub_tools(category: str | None = None, keyword: str | None = None) -> dict[str, Any]:
    """查询 KnowHub 工具表

    Args:
        category: 工具分类（可选）：image_gen, image_process, model, plugin, workflow, other
        keyword: 关键词搜索（可选）

    Returns:
        查询结果，包含工具列表和统计信息
    """
    client = get_client()

    if category:
        tools = client.search_tools_by_category(category)
    else:
        tools = client.list_all_tools()

    # 关键词过滤
    if keyword:
        keyword_lower = keyword.lower()
        tools = [
            t for t in tools
            if keyword_lower in t.get("title", "").lower()
            or keyword_lower in t.get("metadata", {}).get("description", "").lower()
            or keyword_lower in t.get("metadata", {}).get("tool_slug", "").lower()
        ]

    return {
        "status": "success",
        "total": len(tools),
        "tools": [
            {
                "tool_id": t.get("id"),
                "title": t.get("title"),
                "category": t.get("metadata", {}).get("category"),
                "status": t.get("metadata", {}).get("status"),
                "description": t.get("metadata", {}).get("description"),
                "knowledge_ids": t.get("metadata", {}).get("knowledge_ids", [])
            }
            for t in tools
        ]
    }


def get_knowhub_tool_detail(tool_id: str) -> dict[str, Any]:
    """获取 KnowHub 工具详情

    Args:
        tool_id: 工具 ID，格式：tools/{category}/{slug}

    Returns:
        工具详情
    """
    client = get_client()
    tool = client.get_tool(tool_id)

    if not tool:
        return {
            "status": "error",
            "message": f"Tool {tool_id} not found"
        }

    metadata = tool.get("metadata", {})
    return {
        "status": "success",
        "tool": {
            "tool_id": tool.get("id"),
            "title": tool.get("title"),
            "category": metadata.get("category"),
            "tool_slug": metadata.get("tool_slug"),
            "status": metadata.get("status"),
            "version": metadata.get("version"),
            "description": metadata.get("description"),
            "usage": metadata.get("usage"),
            "scenarios": metadata.get("scenarios", []),
            "input": metadata.get("input"),
            "output": metadata.get("output"),
            "source": metadata.get("source"),
            "knowledge_ids": metadata.get("knowledge_ids", []),
            "toolhub_items": metadata.get("toolhub_items", []),
            "backend_runtime": metadata.get("backend_runtime")
        }
    }


def sync_tool_to_knowhub(
    tool_id: str,
    name: str,
    category: str,
    description: str,
    backend_runtime: str = "local"
) -> dict[str, Any]:
    """同步 Tool Agent 工具到 KnowHub

    Args:
        tool_id: Tool Agent 中的工具 ID
        name: 工具名称
        category: 工具分类
        description: 工具描述
        backend_runtime: 后端运行时（local/docker/remote）

    Returns:
        同步结果
    """
    client = get_client()
    success = client.sync_tool_from_registry(
        tool_id=tool_id,
        name=name,
        category=category,
        description=description,
        backend_runtime=backend_runtime
    )

    if success:
        return {
            "status": "success",
            "message": f"Tool {tool_id} synced to KnowHub",
            "knowhub_tool_id": f"tools/{category}/{tool_id}"
        }
    else:
        return {
            "status": "error",
            "message": f"Failed to sync tool {tool_id} to KnowHub"
        }


def update_knowhub_tool_status(tool_id: str, new_status: str) -> dict[str, Any]:
    """更新 KnowHub 工具状态

    Args:
        tool_id: 工具 ID，格式：tools/{category}/{slug}
        new_status: 新状态（未接入/已接入/测试中）

    Returns:
        更新结果
    """
    client = get_client()
    success = client.update_tool_status(tool_id, new_status)

    if success:
        return {
            "status": "success",
            "message": f"Tool {tool_id} status updated to '{new_status}'"
        }
    else:
        return {
            "status": "error",
            "message": f"Failed to update tool {tool_id} status"
        }


def update_knowhub_toolhub_items(tool_id: str, toolhub_items: list[dict[str, str]]) -> dict[str, Any]:
    """更新 KnowHub 工具关联的 Tool Agent 工具列表

    Args:
        tool_id: KnowHub 工具 ID，格式：tools/{category}/{slug}
        toolhub_items: Tool Agent 工具列表，每项为 {tool_id: name}
            示例: [{"launch_comfy_env": "启动 ComfyUI 环境"}, {"runcomfy_stop_env": "停止 ComfyUI 环境"}]

    Returns:
        更新结果
    """
    client = get_client()
    success = client.update_toolhub_items(tool_id, toolhub_items)

    if success:
        return {
            "status": "success",
            "message": f"Tool {tool_id} toolhub_items updated ({len(toolhub_items)} items)"
        }
    else:
        return {
            "status": "error",
            "message": f"Failed to update toolhub_items for {tool_id}"
        }
