"""
Configuration settings for BestCDN IP accessibility tester
"""

import json
from typing import Dict, List, Optional
from dataclasses import dataclass

@dataclass
class PerformanceConfig:
    concurrent_requests: int = 100
    request_timeout: float = 3.0
    max_retries: int = 2
    batch_size: int = 1000
    worker_threads: int = 4

@dataclass
class CDNProviderConfig:
    name: str
    enabled: bool = True
    test_domain: str = ""

@dataclass
class TestingConfig:
    protocols: List[str] = None
    user_agent: str = "BestCDN-Tester/1.0"
    follow_redirects: bool = False
    validate_ssl: bool = False

@dataclass
class OutputConfig:
    format: str = "json"
    save_results: bool = True
    output_file: str = "results/accessible_ips.json"
    log_level: str = "info"

class Config:
    def __init__(self, config_file: str = "config.json"):
        self.performance = PerformanceConfig()
        self.testing = TestingConfig(protocols=["http", "https"])
        self.output = OutputConfig()
        
        # CDN Providers configuration
        self.cdn_providers = {
            "edgeone": CDNProviderConfig(
                name="EdgeOne (Tencent Cloud)"
            ),
            "esa": CDNProviderConfig(
                name="ESA (Alibaba Cloud)"
            ),
            "fastly": CDNProviderConfig(
                name="Fastly"
            ),
            "cloudflare": CDNProviderConfig(
                name="Cloudflare"
            )
        }
        
        # Load from file if exists
        try:
            with open(config_file, 'r') as f:
                self._load_from_dict(json.load(f))
        except FileNotFoundError:
            pass
    
    def _load_from_dict(self, config_dict: Dict):
        """Load configuration from dictionary"""
        if "performance" in config_dict:
            perf = config_dict["performance"]
            self.performance = PerformanceConfig(**perf)
        
        if "testing" in config_dict:
            test = config_dict["testing"]
            self.testing = TestingConfig(**test)
        
        if "output" in config_dict:
            output = config_dict["output"]
            self.output = OutputConfig(**output)
        
        if "cdnProviders" in config_dict:
            for provider_key, provider_config in config_dict["cdnProviders"].items():
                if provider_key in self.cdn_providers:
                    # Update existing provider config
                    for key, value in provider_config.items():
                        if hasattr(self.cdn_providers[provider_key], key):
                            setattr(self.cdn_providers[provider_key], key, value)
    
    def set_test_domain(self, provider: str, domain: str):
        """Set test domain for a specific CDN provider"""
        if provider in self.cdn_providers:
            self.cdn_providers[provider].test_domain = domain
    
    def get_enabled_providers(self) -> Dict[str, CDNProviderConfig]:
        """Get all enabled CDN providers"""
        return {k: v for k, v in self.cdn_providers.items() if v.enabled}