#!/usr/bin/env python3
"""
测试优化后的服务管理功能
验证新的添加服务方式和服务详情展示
"""

import sys
import os
import json
import time

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

def test_service_management_imports():
    """测试服务管理模块导入"""
    print("📦 测试服务管理模块导入...")
    
    try:
        from pages.service_management import (
            show, show_service_list, show_add_service, show_service_details,
            add_service_from_form, add_service_from_json, validate_batch_config,
            batch_add_from_json, show_service_edit_form, update_service_config
        )
        print("    ✅ 所有服务管理函数导入成功")
        return True
    except Exception as e:
        print(f"    ❌ 服务管理模块导入失败: {e}")
        return False

def test_add_service_methods():
    """测试添加服务的各种方法"""
    print("\n➕ 测试添加服务方法...")
    
    try:
        from utils.api_client import MCPStoreAPI
        
        # 创建API客户端
        api_client = MCPStoreAPI("http", "http://localhost:18611")
        
        if not api_client.test_connection():
            print("    ⚠️ API服务器未连接，跳过实际测试")
            return True
        
        # 测试1: JSON配置添加单个服务
        print("  - 测试JSON配置添加单个服务...")
        test_service_config = {
            "name": "test_json_service",
            "url": "http://example.com/mcp",
            "description": "JSON配置测试服务",
            "transport": "auto"
        }
        
        response = api_client.add_service(test_service_config)
        if response:
            print("    ✅ JSON配置添加服务API调用成功")
        else:
            print("    ⚠️ JSON配置添加服务API调用失败（可能服务已存在）")
        
        # 测试2: 批量添加服务
        print("  - 测试批量添加服务...")
        batch_services = [
            {
                "name": "test_batch_service_1",
                "url": "http://example1.com/mcp",
                "description": "批量测试服务1"
            },
            {
                "name": "test_batch_service_2", 
                "url": "http://example2.com/mcp",
                "description": "批量测试服务2"
            }
        ]
        
        response = api_client.batch_add_services(batch_services)
        if response:
            print("    ✅ 批量添加服务API调用成功")
        else:
            print("    ⚠️ 批量添加服务API调用失败")
        
        return True
        
    except Exception as e:
        print(f"    ❌ 添加服务方法测试失败: {e}")
        return False

def test_service_operations():
    """测试服务操作功能"""
    print("\n🔧 测试服务操作功能...")
    
    try:
        from utils.api_client import MCPStoreAPI
        
        api_client = MCPStoreAPI("http", "http://localhost:18611")
        
        if not api_client.test_connection():
            print("    ⚠️ API服务器未连接，跳过实际测试")
            return True
        
        # 获取服务列表
        print("  - 测试获取服务列表...")
        response = api_client.list_services()
        if response and response.get('data'):
            services = response['data']
            print(f"    ✅ 获取到 {len(services)} 个服务")
            
            if services:
                test_service_name = services[0].get('name')
                
                # 测试获取服务详情
                print(f"  - 测试获取服务详情: {test_service_name}")
                detail_response = api_client.get_service_info(test_service_name)
                if detail_response:
                    print("    ✅ 服务详情获取成功")
                else:
                    print("    ⚠️ 服务详情获取失败")
                
                # 测试获取服务状态
                print(f"  - 测试获取服务状态: {test_service_name}")
                status_response = api_client.get_service_status(test_service_name)
                if status_response:
                    print("    ✅ 服务状态获取成功")
                else:
                    print("    ⚠️ 服务状态获取失败")
                
                # 测试重启服务
                print(f"  - 测试重启服务: {test_service_name}")
                restart_response = api_client.restart_service(test_service_name)
                if restart_response:
                    print("    ✅ 服务重启API调用成功")
                else:
                    print("    ⚠️ 服务重启API调用失败")
        else:
            print("    ⚠️ 没有可用服务进行测试")
        
        return True
        
    except Exception as e:
        print(f"    ❌ 服务操作功能测试失败: {e}")
        return False

def test_batch_operations():
    """测试批量操作功能"""
    print("\n📦 测试批量操作功能...")
    
    try:
        from utils.api_client import MCPStoreAPI
        
        api_client = MCPStoreAPI("http", "http://localhost:18611")
        
        if not api_client.test_connection():
            print("    ⚠️ API服务器未连接，跳过实际测试")
            return True
        
        # 测试批量重启（使用不存在的服务名）
        print("  - 测试批量重启服务...")
        test_services = ["non_existent_service_1", "non_existent_service_2"]
        response = api_client.batch_restart_services(test_services)
        if response:
            print("    ✅ 批量重启API调用成功")
        else:
            print("    ⚠️ 批量重启API调用失败")
        
        # 测试批量删除（使用不存在的服务名）
        print("  - 测试批量删除服务...")
        response = api_client.batch_delete_services(test_services)
        if response:
            print("    ✅ 批量删除API调用成功")
        else:
            print("    ⚠️ 批量删除API调用失败")
        
        return True
        
    except Exception as e:
        print(f"    ❌ 批量操作功能测试失败: {e}")
        return False

def test_config_validation():
    """测试配置验证功能"""
    print("\n✅ 测试配置验证功能...")
    
    try:
        from pages.service_management import validate_batch_config
        from utils.helpers import validate_service_name, validate_url
        
        # 测试服务名验证
        print("  - 测试服务名验证...")
        valid_names = ["test_service", "service-1", "my_service_123"]
        invalid_names = ["", "service with spaces", "service@invalid"]
        
        for name in valid_names:
            if validate_service_name(name):
                print(f"    ✅ 有效服务名: {name}")
            else:
                print(f"    ❌ 服务名验证失败: {name}")
        
        for name in invalid_names:
            if not validate_service_name(name):
                print(f"    ✅ 正确拒绝无效服务名: {name}")
            else:
                print(f"    ❌ 错误接受无效服务名: {name}")
        
        # 测试URL验证
        print("  - 测试URL验证...")
        valid_urls = ["http://example.com", "https://api.example.com/mcp"]
        invalid_urls = ["not-a-url", "ftp://example.com", ""]
        
        for url in valid_urls:
            if validate_url(url):
                print(f"    ✅ 有效URL: {url}")
            else:
                print(f"    ❌ URL验证失败: {url}")
        
        for url in invalid_urls:
            if not validate_url(url):
                print(f"    ✅ 正确拒绝无效URL: {url}")
            else:
                print(f"    ❌ 错误接受无效URL: {url}")
        
        return True
        
    except Exception as e:
        print(f"    ❌ 配置验证功能测试失败: {e}")
        return False

def test_json_parsing():
    """测试JSON解析功能"""
    print("\n📋 测试JSON解析功能...")
    
    try:
        # 测试有效的JSON配置
        valid_configs = [
            {
                "name": "test_service",
                "url": "http://example.com/mcp"
            },
            {
                "name": "advanced_service",
                "url": "https://api.example.com/mcp",
                "transport": "sse",
                "description": "高级服务配置",
                "timeout": 60,
                "headers": {"Authorization": "Bearer token"},
                "env": {"API_KEY": "secret"}
            }
        ]
        
        for i, config in enumerate(valid_configs):
            json_str = json.dumps(config, indent=2)
            try:
                parsed = json.loads(json_str)
                print(f"    ✅ 有效JSON配置 {i+1}: 解析成功")
            except json.JSONDecodeError:
                print(f"    ❌ 有效JSON配置 {i+1}: 解析失败")
        
        # 测试批量配置
        batch_config = [
            {"name": "service1", "url": "http://example1.com/mcp"},
            {"name": "service2", "url": "http://example2.com/mcp"}
        ]
        
        batch_json = json.dumps(batch_config, indent=2)
        try:
            parsed_batch = json.loads(batch_json)
            if isinstance(parsed_batch, list):
                print(f"    ✅ 批量JSON配置: 解析成功 ({len(parsed_batch)} 个服务)")
            else:
                print("    ❌ 批量JSON配置: 格式错误")
        except json.JSONDecodeError:
            print("    ❌ 批量JSON配置: 解析失败")
        
        return True
        
    except Exception as e:
        print(f"    ❌ JSON解析功能测试失败: {e}")
        return False

def main():
    """主测试函数"""
    print("🧪 服务管理功能测试")
    print("=" * 50)
    
    tests = [
        ("模块导入", test_service_management_imports),
        ("添加服务方法", test_add_service_methods),
        ("服务操作功能", test_service_operations),
        ("批量操作功能", test_batch_operations),
        ("配置验证功能", test_config_validation),
        ("JSON解析功能", test_json_parsing)
    ]
    
    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("🎉 所有服务管理功能测试通过！")
        print("✅ 优化后的服务管理功能可以正常使用")
    else:
        print("⚠️ 部分服务管理功能测试失败，请检查相关模块")
    
    return passed == total

if __name__ == "__main__":
    main()
