import requests
import json
import time
from typing import Dict, Any, List

class SystemTester:
    def __init__(self, base_url: str = "http://localhost:8001/api/v1"):
        self.base_url = base_url
        self.session = requests.Session()
        self.token = None
        self.user_id = None
    
    def login(self, username: str = "admin", password: str = "admin123") -> bool:
        """登录系统"""
        try:
            response = self.session.post(
                f"{self.base_url}/users/login",
                json={"username": username, "password": password}
            )
            if response.status_code == 200:
                data = response.json()
                self.token = data.get("access_token")
                self.user_id = data.get("user_id")
                self.session.headers.update({"Authorization": f"Bearer {self.token}"})
                print(f"✓ 登录成功: {username}")
                return True
            else:
                print(f"✗ 登录失败: {response.status_code} - {response.text}")
                return False
        except Exception as e:
            print(f"✗ 登录异常: {str(e)}")
            return False
    
    def test_config_endpoints(self) -> bool:
        """测试配置管理API"""
        print("\n=== 测试配置管理API ===")
        success = True
        
        try:
            # 测试获取所有配置
            response = self.session.get(f"{self.base_url}/config/")
            if response.status_code == 200:
                print("✓ 获取所有配置成功")
                configs = response.json().get("configs", [])
                print(f"  当前配置数量: {len(configs)}")
            else:
                print(f"✗ 获取所有配置失败: {response.status_code}")
                success = False
            
            # 测试添加配置
            test_config = {
                "value": "test_value_123",
                "type": "system",
                "service_id": None,
                "description": "测试配置"
            }
            response = self.session.post(f"{self.base_url}/config/test_config_key", json=test_config)
            if response.status_code == 200:
                print("✓ 添加配置成功")
            else:
                print(f"✗ 添加配置失败: {response.status_code} - {response.text}")
                success = False
            
            # 测试获取单个配置
            response = self.session.get(f"{self.base_url}/config/test_config_key")
            if response.status_code == 200:
                print("✓ 获取单个配置成功")
                config_data = response.json()
                print(f"  配置值: {config_data.get('value')}")
            else:
                print(f"✗ 获取单个配置失败: {response.status_code}")
                success = False
            
            # 测试删除配置
            response = self.session.delete(f"{self.base_url}/config/test_config_key")
            if response.status_code == 200:
                print("✓ 删除配置成功")
            else:
                print(f"✗ 删除配置失败: {response.status_code}")
                success = False
            
            return success
        except Exception as e:
            print(f"✗ 配置管理API测试异常: {str(e)}")
            return False
    
    def test_comparison_endpoints(self) -> bool:
        """测试算法比较API"""
        print("\n=== 测试算法比较API ===")
        success = True
        
        try:
            # 测试算法比较（使用模拟数据）
            test_data = {
                "input_data": {"text": "这是一段测试文本"},
                "algorithm_configs": [
                    {
                        "algorithm_id": "test_algo_1",
                        "algorithm_name": "测试算法1",
                        "version": "1.0.0",
                        "config": "{}"
                    },
                    {
                        "algorithm_id": "test_algo_2",
                        "algorithm_name": "测试算法2",
                        "version": "1.0.0",
                        "config": "{}"
                    }
                ]
            }
            
            response = self.session.post(f"{self.base_url}/comparison/compare-algorithms", json=test_data)
            if response.status_code == 200:
                print("✓ 算法比较API调用成功")
                result = response.json()
                print(f"  比较状态: {result.get('success')}")
                if result.get('results'):
                    print(f"  结果数量: {len(result.get('results'))}")
            else:
                print(f"✗ 算法比较失败: {response.status_code} - {response.text}")
                success = False
            
            return success
        except Exception as e:
            print(f"✗ 算法比较API测试异常: {str(e)}")
            return False
    
    def test_existing_endpoints(self) -> bool:
        """测试现有API端点"""
        print("\n=== 测试现有API端点 ===")
        success = True
        
        try:
            # 测试健康检查
            response = self.session.get(f"{self.base_url.replace('/api/v1', '')}/health")
            if response.status_code == 200:
                print("✓ 健康检查通过")
            else:
                print(f"✗ 健康检查失败: {response.status_code}")
                success = False
            
            # 测试获取当前用户
            response = self.session.get(f"{self.base_url}/users/me")
            if response.status_code == 200:
                print("✓ 获取当前用户成功")
                user_data = response.json()
                print(f"  用户名: {user_data.get('username')}")
            else:
                print(f"✗ 获取当前用户失败: {response.status_code}")
                success = False
            
            # 测试获取算法列表
            response = self.session.get(f"{self.base_url}/algorithms/")
            if response.status_code == 200:
                print("✓ 获取算法列表成功")
                algorithms = response.json()
                print(f"  算法数量: {len(algorithms) if isinstance(algorithms, list) else 0}")
            else:
                print(f"✗ 获取算法列表失败: {response.status_code}")
                success = False
            
            # 测试获取服务列表
            response = self.session.get(f"{self.base_url}/services")
            if response.status_code == 200:
                print("✓ 获取服务列表成功")
                services = response.json()
                print(f"  服务数量: {len(services) if isinstance(services, list) else 0}")
            else:
                print(f"✗ 获取服务列表失败: {response.status_code}")
                success = False
            
            return success
        except Exception as e:
            print(f"✗ 现有API端点测试异常: {str(e)}")
            return False
    
    def run_all_tests(self) -> Dict[str, bool]:
        """运行所有测试"""
        print("=" * 50)
        print("开始系统自动化测试")
        print("=" * 50)
        
        results = {}
        
        # 登录
        if not self.login():
            print("\n✗ 登录失败，无法继续测试")
            return {"login": False}
        
        results["login"] = True
        
        # 测试现有端点
        results["existing_endpoints"] = self.test_existing_endpoints()
        
        # 测试配置管理API
        results["config_endpoints"] = self.test_config_endpoints()
        
        # 测试算法比较API
        results["comparison_endpoints"] = self.test_comparison_endpoints()
        
        # 输出测试结果
        print("\n" + "=" * 50)
        print("测试结果汇总")
        print("=" * 50)
        
        for test_name, result in results.items():
            status = "✓ 通过" if result else "✗ 失败"
            print(f"{test_name}: {status}")
        
        total_tests = len(results)
        passed_tests = sum(1 for result in results.values() if result)
        
        print(f"\n总计: {passed_tests}/{total_tests} 测试通过")
        
        if passed_tests == total_tests:
            print("🎉 所有测试通过！")
        else:
            print("⚠️  部分测试失败，请检查日志")
        
        return results

def main():
    """主函数"""
    tester = SystemTester()
    results = tester.run_all_tests()
    
    # 返回退出码
    exit_code = 0 if all(results.values()) else 1
    return exit_code

if __name__ == "__main__":
    exit(main())