#!/usr/bin/env python3
"""
测试更新后的API接口
验证新添加的配置验证和状态查询API
"""

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

from utils.api_client import MCPStoreAPI

def test_new_config_apis():
    """测试新增的配置相关API"""
    print("🔧 测试新增配置API...")
    
    # 创建API客户端
    api_client = MCPStoreAPI("http", "http://localhost:18611")
    
    # 测试Store配置验证
    print("  - 测试Store配置验证...")
    try:
        result = api_client.validate_config()
        if result:
            print(f"    ✅ Store配置验证成功: {result.get('data', {}).get('valid', False)}")
        else:
            print("    ❌ Store配置验证失败")
    except Exception as e:
        print(f"    ⚠️ Store配置验证异常: {e}")
    
    # 测试Agent配置验证
    test_agent_id = "test_agent_001"
    print(f"  - 测试Agent配置验证: {test_agent_id}")
    try:
        result = api_client.validate_agent_config(test_agent_id)
        if result:
            print(f"    ✅ Agent配置验证成功: {result.get('data', {}).get('valid', False)}")
        else:
            print("    ⚠️ Agent配置验证失败（可能Agent不存在）")
    except Exception as e:
        print(f"    ⚠️ Agent配置验证异常: {e}")
    
    # 测试Agent配置获取
    print(f"  - 测试Agent配置获取: {test_agent_id}")
    try:
        result = api_client.get_agent_config(test_agent_id)
        if result:
            print("    ✅ Agent配置获取成功")
        else:
            print("    ⚠️ Agent配置获取失败（可能Agent不存在）")
    except Exception as e:
        print(f"    ⚠️ Agent配置获取异常: {e}")

def test_service_status_api():
    """测试服务状态查询API"""
    print("\n📊 测试服务状态查询API...")
    
    api_client = MCPStoreAPI("http", "http://localhost:18611")
    
    # 先获取服务列表
    print("  - 获取服务列表...")
    try:
        services_result = api_client.list_services()
        if services_result and services_result.get('data'):
            services = services_result['data']
            print(f"    ✅ 找到 {len(services)} 个服务")
            
            # 测试第一个服务的状态查询
            if services:
                first_service = services[0]
                service_name = first_service.get('name')
                if service_name:
                    print(f"  - 测试服务状态查询: {service_name}")
                    try:
                        status_result = api_client.get_service_status(service_name)
                        if status_result:
                            print("    ✅ 服务状态查询成功")
                            status_data = status_result.get('data', {})
                            print(f"    📈 服务状态: {status_data.get('health', {}).get('status', 'unknown')}")
                        else:
                            print("    ❌ 服务状态查询失败")
                    except Exception as e:
                        print(f"    ⚠️ 服务状态查询异常: {e}")
        else:
            print("    ⚠️ 没有找到服务，跳过状态查询测试")
    except Exception as e:
        print(f"    ❌ 获取服务列表失败: {e}")

def test_api_methods_existence():
    """测试API方法是否存在"""
    print("\n🔍 测试API方法存在性...")
    
    api_client = MCPStoreAPI("http", "http://localhost:18611")
    
    # 检查新增的方法
    new_methods = [
        'validate_config',
        'get_service_status', 
        'validate_agent_config',
        'get_agent_config',
        'show_agent_mcpconfig',
        'update_agent_config'
    ]
    
    for method_name in new_methods:
        if hasattr(api_client, method_name):
            print(f"    ✅ {method_name} - 方法存在")
        else:
            print(f"    ❌ {method_name} - 方法缺失")

def test_api_connection():
    """测试API连接"""
    print("🔗 测试API连接...")
    
    api_client = MCPStoreAPI("http", "http://localhost:18611")
    
    if api_client.test_connection():
        print("    ✅ API连接成功")
        return True
    else:
        print("    ❌ API连接失败")
        return False

def main():
    """主测试函数"""
    print("🧪 MCPStore 更新API测试")
    print("=" * 50)
    
    # 测试连接
    if not test_api_connection():
        print("❌ 无法连接到API服务器，请确保MCPStore API服务正在运行")
        return
    
    try:
        # 测试方法存在性
        test_api_methods_existence()
        
        # 测试新增配置API
        test_new_config_apis()
        
        # 测试服务状态API
        test_service_status_api()
        
        print("\n" + "=" * 50)
        print("✅ 更新API测试完成")
        print("📝 注意：部分API可能因为Agent不存在而返回失败，这是正常的")
        
    except Exception as e:
        print(f"\n❌ 测试过程中发生错误: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    main()
