"""
智能算法展示平台 - 集成测试配置

此配置文件定义了集成测试所需的设置和参数。
"""

import os
from typing import Dict, Any, Optional


class IntegrationTestConfig:
    """集成测试配置类"""
    
    def __init__(self):
        # 基础URL配置
        self.base_url = os.getenv('TEST_BASE_URL', 'http://localhost:8000')
        self.api_version = '/api/v1'
        
        # 认证配置
        self.api_key = os.getenv('TEST_API_KEY', 'test-key-12345')
        self.auth_headers = {
            'Authorization': f'Bearer {self.api_key}',
            'Content-Type': 'application/json'
        }
        
        # 测试数据配置
        self.test_timeout = int(os.getenv('TEST_TIMEOUT', '30'))
        self.retry_count = int(os.getenv('TEST_RETRY_COUNT', '3'))
        self.delay_between_retries = float(os.getenv('TEST_DELAY_BETWEEN_RETRIES', '1.0'))
        
        # 服务配置
        self.backend_port = int(os.getenv('BACKEND_PORT', '8000'))
        self.frontend_port = int(os.getenv('FRONTEND_PORT', '3000'))
        self.db_host = os.getenv('DB_HOST', 'localhost')
        self.db_port = int(os.getenv('DB_PORT', '5432'))
        
        # 测试算法配置
        self.test_algorithms = [
            {
                'name': 'Image Classification Test Algorithm',
                'description': 'Test algorithm for image classification',
                'type': 'computer_vision',
                'status': 'active',
                'input_schema': {
                    'image_url': {'type': 'string', 'required': True}
                },
                'output_schema': {
                    'predictions': {
                        'type': 'array',
                        'items': {
                            'class': {'type': 'string'},
                            'confidence': {'type': 'number'}
                        }
                    }
                }
            },
            {
                'name': 'Text Analysis Test Algorithm',
                'description': 'Test algorithm for text analysis',
                'type': 'nlp',
                'status': 'active',
                'input_schema': {
                    'text': {'type': 'string', 'required': True}
                },
                'output_schema': {
                    'sentiment': {'type': 'string'},
                    'entities': {'type': 'array', 'items': {'type': 'string'}}
                }
            }
        ]
        
        # 测试输入数据
        self.test_inputs = {
            'computer_vision': {
                'image_url': 'https://example.com/test-image.jpg'
            },
            'nlp': {
                'text': 'This is a test text for NLP algorithm.'
            },
            'ml': {
                'features': [1.0, 2.0, 3.0, 4.0, 5.0]
            }
        }
        
        # 测试参数
        self.test_params = {
            'confidence_threshold': 0.7,
            'max_results': 10,
            'return_probabilities': True
        }
    
    def get_api_url(self, endpoint: str) -> str:
        """获取API端点的完整URL"""
        return f"{self.base_url}{self.api_version}{endpoint}"
    
    def get_auth_headers(self) -> Dict[str, str]:
        """获取认证头部信息"""
        return self.auth_headers.copy()
    
    def get_test_algorithm_by_type(self, alg_type: str) -> Optional[Dict[str, Any]]:
        """根据类型获取测试算法配置"""
        for alg in self.test_algorithms:
            if alg['type'] == alg_type:
                return alg
        return None


# 全局配置实例
test_config = IntegrationTestConfig()


def get_test_config() -> IntegrationTestConfig:
    """获取测试配置实例"""
    return test_config


# 环境特定的配置
class TestEnvironment:
    """测试环境配置"""
    
    LOCAL = "local"
    DOCKER = "docker"
    CI_CD = "ci_cd"
    
    @staticmethod
    def detect_environment() -> str:
        """检测当前测试环境"""
        if os.getenv('CI'):
            return TestEnvironment.CI_CD
        elif os.getenv('DOCKER_ENV'):
            return TestEnvironment.DOCKER
        else:
            return TestEnvironment.LOCAL
    
    @staticmethod
    def get_environment_config(env_type: str) -> Dict[str, Any]:
        """获取特定环境的配置"""
        configs = {
            TestEnvironment.LOCAL: {
                'base_url': 'http://localhost:8000',
                'db_url': 'postgresql://user:password@localhost:5432/test_db',
                'redis_url': 'redis://localhost:6379/0',
                'minio_url': 'http://localhost:9000'
            },
            TestEnvironment.DOCKER: {
                'base_url': 'http://backend:8000',
                'db_url': 'postgresql://user:password@db:5432/test_db',
                'redis_url': 'redis://redis:6379/0',
                'minio_url': 'http://minio:9000'
            },
            TestEnvironment.CI_CD: {
                'base_url': os.getenv('TEST_BASE_URL', 'http://localhost:8000'),
                'db_url': os.getenv('TEST_DB_URL', 'postgresql://user:password@localhost:5432/test_db'),
                'redis_url': os.getenv('TEST_REDIS_URL', 'redis://localhost:6379/0'),
                'minio_url': os.getenv('TEST_MINIO_URL', 'http://localhost:9000')
            }
        }
        return configs.get(env_type, configs[TestEnvironment.LOCAL])


# 数据工厂类，用于生成测试数据
class TestDataFactory:
    """测试数据工厂"""
    
    @staticmethod
    def create_algorithm_data(name_suffix: str = "") -> Dict[str, Any]:
        """创建算法测试数据"""
        import uuid
        from datetime import datetime
        
        return {
            'id': f'test-alg-{uuid.uuid4().hex[:8]}',
            'name': f'Test Algorithm {name_suffix}'.strip() or f'Test Algorithm {uuid.uuid4().hex[:8]}',
            'description': f'Test algorithm for integration testing {datetime.now().isoformat()}',
            'type': 'computer_vision',
            'status': 'active',
            'versions': [],
            'created_at': datetime.now().isoformat(),
            'updated_at': datetime.now().isoformat()
        }
    
    @staticmethod
    def create_call_data(algorithm_id: str, version_id: str = None) -> Dict[str, Any]:
        """创建算法调用测试数据"""
        import uuid
        
        return {
            'id': f'test-call-{uuid.uuid4().hex[:8]}',
            'user_id': f'test-user-{uuid.uuid4().hex[:8]}',
            'algorithm_id': algorithm_id,
            'version_id': version_id or f'test-ver-{uuid.uuid4().hex[:8]}',
            'input_data': {'test': 'data'},
            'params': {'test_param': 'test_value'},
            'output_data': {'result': 'test_result'},
            'status': 'success',
            'response_time': 0.123,
            'error_message': None,
            'created_at': datetime.now().isoformat(),
            'updated_at': datetime.now().isoformat()
        }


# 测试助手类
class TestHelpers:
    """测试助手类，提供常用的测试辅助功能"""
    
    @staticmethod
    def wait_for_service(url: str, timeout: int = 30, interval: float = 1.0) -> bool:
        """等待服务启动"""
        import time
        import requests
        from requests.exceptions import RequestException
        
        start_time = time.time()
        while time.time() - start_time < timeout:
            try:
                response = requests.get(url, timeout=5)
                if response.status_code == 200:
                    return True
            except RequestException:
                pass
            
            time.sleep(interval)
        
        return False
    
    @staticmethod
    def cleanup_test_data(api_url: str, headers: Dict[str, str], test_ids: list):
        """清理测试数据"""
        import requests
        
        # 这里可以添加清理测试数据的逻辑
        # 例如删除测试算法、清理测试调用记录等
        print(f"清理测试数据: {test_ids}")


# 用于运行测试的装饰器
def retry_on_failure(max_attempts: int = 3, delay: float = 1.0):
    """失败重试装饰器"""
    def decorator(func):
        def wrapper(*args, **kwargs):
            last_exception = None
            for attempt in range(max_attempts):
                try:
                    return func(*args, **kwargs)
                except Exception as e:
                    last_exception = e
                    if attempt < max_attempts - 1:
                        import time
                        time.sleep(delay)
                    else:
                        raise e
            raise last_exception
        return wrapper
    return decorator


if __name__ == "__main__":
    # 输出当前配置信息
    config = get_test_config()
    env = TestEnvironment.detect_environment()
    
    print(f"测试环境: {env}")
    print(f"基础URL: {config.base_url}")
    print(f"API密钥: {'*' * len(config.api_key) if config.api_key else '未设置'}")
    print(f"超时时间: {config.test_timeout}秒")
    print(f"重试次数: {config.retry_count}")
    
    env_config = TestEnvironment.get_environment_config(env)
    print(f"环境特定配置: {env_config}")