#!/usr/bin/env python3
"""
测试新实现的功能
包括批量操作API和工具使用历史记录
"""

import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from utils.api_client import MCPStoreAPI
from utils.tool_history import (
    record_tool_usage, get_tool_statistics, get_tool_history, clear_tool_history
)
import time
import json

def test_batch_operations():
    """测试批量操作API"""
    print("🔧 测试批量操作API...")
    
    # 创建API客户端
    api_client = MCPStoreAPI("http", "http://localhost:18611")
    
    if not api_client.test_connection():
        print("❌ 无法连接到API服务器")
        return False
    
    # 测试批量重启服务
    print("  - 测试批量重启服务...")
    try:
        # 先获取服务列表
        services_response = api_client.list_services()
        if services_response and services_response.get('data'):
            service_names = [s.get('name') for s in services_response['data'][:2]]  # 取前2个服务
            
            if service_names:
                result = api_client.batch_restart_services(service_names)
                if result and result.get('success'):
                    print(f"    ✅ 批量重启成功: {result.get('message')}")
                    summary = result.get('data', {}).get('summary', {})
                    print(f"    📊 统计: 总数={summary.get('total', 0)}, 成功={summary.get('success', 0)}")
                else:
                    print(f"    ❌ 批量重启失败: {result.get('message') if result else '无响应'}")
            else:
                print("    ⚠️ 没有可用服务进行测试")
        else:
            print("    ⚠️ 无法获取服务列表")
    except Exception as e:
        print(f"    ❌ 批量重启测试异常: {e}")
    
    # 测试批量删除服务（使用不存在的服务名，避免影响实际服务）
    print("  - 测试批量删除服务...")
    try:
        test_service_names = ["test_service_1", "test_service_2"]
        result = api_client.batch_delete_services(test_service_names)
        if result:
            print(f"    ✅ 批量删除API调用成功: {result.get('message')}")
            summary = result.get('data', {}).get('summary', {})
            print(f"    📊 统计: 总数={summary.get('total', 0)}, 成功={summary.get('success', 0)}")
        else:
            print("    ❌ 批量删除API调用失败")
    except Exception as e:
        print(f"    ❌ 批量删除测试异常: {e}")
    
    return True

def test_tool_history():
    """测试工具使用历史功能"""
    print("\n📝 测试工具使用历史功能...")
    
    # 清空历史记录
    clear_tool_history()
    print("  - 已清空历史记录")
    
    # 模拟一些工具使用记录
    test_records = [
        {
            "tool_name": "weather_query",
            "args": {"city": "北京"},
            "result": {"temperature": "25°C", "weather": "晴天"},
            "success": True,
            "execution_time": 1.2
        },
        {
            "tool_name": "map_search",
            "args": {"query": "天安门"},
            "result": {"lat": 39.9042, "lng": 116.4074},
            "success": True,
            "execution_time": 0.8
        },
        {
            "tool_name": "weather_query",
            "args": {"city": "上海"},
            "result": {"error": "API限制"},
            "success": False,
            "execution_time": 2.1
        },
        {
            "tool_name": "translate",
            "args": {"text": "Hello", "target": "zh"},
            "result": {"translated": "你好"},
            "success": True,
            "execution_time": 0.5
        }
    ]
    
    # 添加测试记录
    print("  - 添加测试记录...")
    for record in test_records:
        record_tool_usage(
            tool_name=record["tool_name"],
            args=record["args"],
            result=record["result"],
            success=record["success"],
            execution_time=record["execution_time"]
        )
        time.sleep(0.1)  # 确保时间戳不同
    
    print(f"    ✅ 已添加 {len(test_records)} 条测试记录")
    
    # 测试历史查询
    print("  - 测试历史查询...")
    history = get_tool_history(limit=10)
    print(f"    ✅ 查询到 {len(history)} 条历史记录")
    
    # 测试统计功能
    print("  - 测试统计功能...")
    stats = get_tool_statistics()
    print(f"    ✅ 统计结果:")
    print(f"      - 总执行次数: {stats['total_executions']}")
    print(f"      - 使用过的工具: {stats['unique_tools']}")
    print(f"      - 成功率: {stats['success_rate']:.1f}%")
    print(f"      - 平均执行时间: {stats['avg_execution_time']:.2f}秒")
    
    # 显示工具使用排行
    if stats['tool_usage']:
        print("    📊 工具使用排行:")
        sorted_tools = sorted(stats['tool_usage'].items(), 
                            key=lambda x: x[1]['count'], reverse=True)
        for i, (tool_name, tool_data) in enumerate(sorted_tools[:3]):
            print(f"      {i+1}. {tool_name}: {tool_data['count']}次 (成功率: {tool_data['success_rate']:.1f}%)")
    
    return True

def test_api_methods_existence():
    """测试新API方法是否存在"""
    print("\n🔍 测试新API方法存在性...")
    
    api_client = MCPStoreAPI("http", "http://localhost:18611")
    
    # 检查批量操作方法
    batch_methods = [
        'batch_restart_services',
        'batch_delete_services',
        'batch_update_services'
    ]
    
    for method_name in batch_methods:
        if hasattr(api_client, method_name):
            print(f"    ✅ {method_name} - 方法存在")
        else:
            print(f"    ❌ {method_name} - 方法缺失")
    
    # 检查配置相关方法
    config_methods = [
        'validate_config',
        'get_service_status',
        'validate_agent_config',
        'get_agent_config',
        'show_agent_mcpconfig',
        'update_agent_config'
    ]
    
    for method_name in config_methods:
        if hasattr(api_client, method_name):
            print(f"    ✅ {method_name} - 方法存在")
        else:
            print(f"    ❌ {method_name} - 方法缺失")
    
    return True

def test_tool_history_integration():
    """测试工具历史集成"""
    print("\n🧪 测试工具历史集成...")
    
    try:
        from utils.tool_history import (
            show_tool_statistics_ui, show_tool_history_ui, get_history_manager
        )
        print("    ✅ 工具历史模块导入成功")
        
        # 测试历史管理器
        manager = get_history_manager()
        print(f"    ✅ 历史管理器创建成功: {type(manager).__name__}")
        
        # 测试统计数据
        stats = manager.get_statistics()
        print(f"    ✅ 统计数据获取成功: {stats['total_executions']} 条记录")
        
        return True
    except Exception as e:
        print(f"    ❌ 工具历史集成测试失败: {e}")
        return False

def main():
    """主测试函数"""
    print("🧪 MCPStore 新功能测试")
    print("=" * 50)
    
    tests = [
        ("API方法存在性", test_api_methods_existence),
        ("批量操作API", test_batch_operations),
        ("工具使用历史", test_tool_history),
        ("工具历史集成", test_tool_history_integration)
    ]
    
    passed = 0
    total = len(tests)
    
    for test_name, test_func in tests:
        print(f"\n🔬 运行测试: {test_name}")
        try:
            if test_func():
                passed += 1
                print(f"✅ {test_name} - 通过")
            else:
                print(f"❌ {test_name} - 失败")
        except Exception as e:
            print(f"❌ {test_name} - 异常: {e}")
        
        print("-" * 30)
    
    print(f"\n📊 测试结果: {passed}/{total} 通过")
    
    if passed == total:
        print("🎉 所有测试通过！新功能实现成功")
    else:
        print("⚠️ 部分测试失败，请检查实现")

if __name__ == "__main__":
    main()
