"""测试 KnowHub 工具表 API 集成

验证 FastAPI 路由是否正确调用 tool_table_tools 模块
"""

import sys
from pathlib import Path

# 添加项目根目录到 Python 路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root / "src"))

from tool_agent.router import tool_table_tools


def test_query_all_tools():
    """测试查询所有工具"""
    print("\n=== 测试：查询所有工具 ===")
    result = tool_table_tools.query_knowhub_tools()

    print(f"状态: {result['status']}")
    print(f"工具总数: {result['total']}")

    if result['total'] > 0:
        print(f"\n前 3 个工具:")
        for tool in result['tools'][:3]:
            print(f"  - {tool['title']} ({tool['tool_id']})")
            print(f"    分类: {tool['category']}, 状态: {tool['status']}")


def test_query_by_category():
    """测试按分类查询"""
    print("\n=== 测试：按分类查询 (plugin) ===")
    result = tool_table_tools.query_knowhub_tools(category="plugin")

    print(f"状态: {result['status']}")
    print(f"plugin 类工具数: {result['total']}")

    for tool in result['tools'][:5]:
        print(f"  - {tool['title']} | 状态: {tool['status']}")


def test_query_by_keyword():
    """测试关键词搜索"""
    print("\n=== 测试：关键词搜索 (comfyui) ===")
    result = tool_table_tools.query_knowhub_tools(keyword="comfyui")

    print(f"状态: {result['status']}")
    print(f"匹配工具数: {result['total']}")

    for tool in result['tools']:
        print(f"  - {tool['title']} ({tool['tool_id']})")
        print(f"    状态: {tool['status']}")


def test_get_tool_detail():
    """测试获取工具详情"""
    print("\n=== 测试：获取工具详情 (tools/image_gen/comfyui) ===")
    result = tool_table_tools.get_knowhub_tool_detail("tools/image_gen/comfyui")

    print(f"状态: {result['status']}")
    if result['status'] == 'success':
        tool = result['tool']
        print(f"标题: {tool['title']}")
        print(f"分类: {tool['category']}")
        print(f"接入状态: {tool['status']}")
        print(f"描述: {tool['description']}")
        print(f"使用方法: {tool['usage']}")
        print(f"应用场景: {tool['scenarios']}")
        print(f"关联知识数: {len(tool['knowledge_ids'])}")


def test_update_comfyui_status():
    """测试更新 ComfyUI 状态为已接入"""
    print("\n=== 测试：更新 ComfyUI 状态为已接入 ===")
    result = tool_table_tools.update_knowhub_tool_status(
        "tools/image_gen/comfyui", "已接入"
    )

    print(f"状态: {result['status']}")
    print(f"消息: {result['message']}")

    # 验证
    print("\n验证更新结果:")
    detail = tool_table_tools.get_knowhub_tool_detail("tools/image_gen/comfyui")
    if detail['status'] == 'success':
        print(f"当前状态: {detail['tool']['status']}")


def main():
    print("=" * 60)
    print("KnowHub 工具表 API 集成测试")
    print("=" * 60)

    test_query_all_tools()
    test_query_by_category()
    test_query_by_keyword()
    test_get_tool_detail()
    test_update_comfyui_status()

    print("\n" + "=" * 60)
    print("测试完成！")


if __name__ == "__main__":
    main()
