"""
Phase 3 Configuration and Settings
Advanced configuration for Phase 3 features

Author: Pezhman Hajipour
Version: 3.0.0
"""

from dataclasses import dataclass
from typing import Dict, List, Optional, Any
# Phase 3 modules imported through main package imports

@dataclass
class Phase3Config:
    """Configuration for Phase 3 advanced features"""
    
    # Machine Learning Settings
    ml_model_enabled: bool = True
    ml_model_path: str = "/models/"
    ml_confidence_threshold: float = 0.75
    ml_training_frequency_hours: int = 6
    ml_feature_count: int = 25
    
    # Cross-Chain Settings
    cross_chain_enabled: bool = True
    cross_chain_scan_frequency_seconds: int = 30
    coordination_score_threshold: float = 0.8
    supported_chains: List[str] = None
    
    # Dashboard Settings  
    dashboard_enabled: bool = True
    dashboard_port: int = 8080
    dashboard_update_frequency_seconds: int = 5
    max_dashboard_connections: int = 100
    
    # Alert System Settings
    advanced_alerts_enabled: bool = True
    alert_cooldown_seconds: int = 30
    max_active_alerts: int = 50
    alert_escalation_enabled: bool = True
    
    # Portfolio Optimization Settings
    portfolio_optimization_enabled: bool = True
    optimization_frequency_hours: int = 4
    max_position_allocation: float = 0.25
    min_opportunity_confidence: float = 0.6
    rebalancing_threshold: float = 0.05
    
    # Advanced Analytics Settings
    pattern_detection_enabled: bool = True
    correlation_analysis_enabled: bool = True
    sentiment_analysis_depth: str = "ADVANCED"  # BASIC, ADVANCED, EXPERT
    
    # Performance Settings
    max_concurrent_processes: int = 10
    cache_timeout_minutes: int = 15
    database_retention_days: int = 30
    
    # Integration Settings
    api_rate_limit_per_minute: int = 1000
    webhook_enabled: bool = True
    webhook_url: Optional[str] = None
    
    def __post_init__(self):
        if self.supported_chains is None:
            self.supported_chains = [
                'ETHEREUM', 'POLYGON', 'BSC', 'ARBITRUM', 
                'OPTIMISM', 'AVALANCHE', 'FANTOM'
            ]

# Default Phase 3 configuration
DEFAULT_PHASE3_CONFIG = Phase3Config()

# Production configuration
PRODUCTION_PHASE3_CONFIG = Phase3Config(
    ml_model_enabled=True,
    cross_chain_enabled=True,
    dashboard_enabled=True,
    advanced_alerts_enabled=True,
    portfolio_optimization_enabled=True,
    pattern_detection_enabled=True,
    correlation_analysis_enabled=True,
    sentiment_analysis_depth="EXPERT",
    max_concurrent_processes=20,
    cache_timeout_minutes=30,
    database_retention_days=90,
    api_rate_limit_per_minute=2000,
    webhook_enabled=True
)

# Development configuration  
DEVELOPMENT_PHASE3_CONFIG = Phase3Config(
    ml_model_enabled=True,
    cross_chain_enabled=False,  # Disabled for faster development
    dashboard_enabled=True,
    advanced_alerts_enabled=True,
    portfolio_optimization_enabled=True,
    pattern_detection_enabled=True,
    correlation_analysis_enabled=True,
    sentiment_analysis_depth="ADVANCED",
    max_concurrent_processes=5,
    cache_timeout_minutes=5,
    database_retention_days=7,
    api_rate_limit_per_minute=500,
    webhook_enabled=False
)

# Testing configuration
TEST_PHASE3_CONFIG = Phase3Config(
    ml_model_enabled=False,
    cross_chain_enabled=False,
    dashboard_enabled=False,
    advanced_alerts_enabled=True,
    portfolio_optimization_enabled=False,
    pattern_detection_enabled=False,
    correlation_analysis_enabled=False,
    sentiment_analysis_depth="BASIC",
    max_concurrent_processes=2,
    cache_timeout_minutes=1,
    database_retention_days=1,
    api_rate_limit_per_minute=100,
    webhook_enabled=False
)

def get_phase3_config(config_type: str = "default") -> Phase3Config:
    """Get Phase 3 configuration by type"""
    config_map = {
        "default": DEFAULT_PHASE3_CONFIG,
        "production": PRODUCTION_PHASE3_CONFIG,
        "development": DEVELOPMENT_PHASE3_CONFIG,
        "test": TEST_PHASE3_CONFIG
    }
    
    return config_map.get(config_type.lower(), DEFAULT_PHASE3_CONFIG)

def create_custom_phase3_config(**kwargs) -> Phase3Config:
    """Create custom Phase 3 configuration"""
    config = Phase3Config()
    
    for key, value in kwargs.items():
        if hasattr(config, key):
            setattr(config, key, value)
        else:
            raise ValueError(f"Unknown configuration parameter: {key}")
    
    return config

# Configuration validation
def validate_phase3_config(config: Phase3Config) -> List[str]:
    """Validate Phase 3 configuration and return any issues"""
    issues = []
    
    # Validate ML settings
    if config.ml_model_enabled:
        if not (0.0 <= config.ml_confidence_threshold <= 1.0):
            issues.append("ML confidence threshold must be between 0.0 and 1.0")
        
        if config.ml_training_frequency_hours < 1:
            issues.append("ML training frequency must be at least 1 hour")
    
    # Validate cross-chain settings
    if config.cross_chain_enabled:
        if config.coordination_score_threshold < 0.0 or config.coordination_score_threshold > 1.0:
            issues.append("Coordination score threshold must be between 0.0 and 1.0")
    
    # Validate dashboard settings
    if config.dashboard_enabled:
        if not (1024 <= config.dashboard_port <= 65535):
            issues.append("Dashboard port must be between 1024 and 65535")
        
        if config.dashboard_update_frequency_seconds < 1:
            issues.append("Dashboard update frequency must be at least 1 second")
    
    # Validate alert settings
    if config.advanced_alerts_enabled:
        if config.alert_cooldown_seconds < 1:
            issues.append("Alert cooldown must be at least 1 second")
        
        if config.max_active_alerts < 1:
            issues.append("Maximum active alerts must be at least 1")
    
    # Validate portfolio settings
    if config.portfolio_optimization_enabled:
        if not (0.0 <= config.max_position_allocation <= 1.0):
            issues.append("Maximum position allocation must be between 0.0 and 1.0")
        
        if not (0.0 <= config.min_opportunity_confidence <= 1.0):
            issues.append("Minimum opportunity confidence must be between 0.0 and 1.0")
        
        if not (0.0 <= config.rebalancing_threshold <= 1.0):
            issues.append("Rebalancing threshold must be between 0.0 and 1.0")
    
    # Validate performance settings
    if config.max_concurrent_processes < 1:
        issues.append("Maximum concurrent processes must be at least 1")
    
    if config.cache_timeout_minutes < 1:
        issues.append("Cache timeout must be at least 1 minute")
    
    if config.database_retention_days < 1:
        issues.append("Database retention must be at least 1 day")
    
    # Validate integration settings
    if config.api_rate_limit_per_minute < 1:
        issues.append("API rate limit must be at least 1 per minute")
    
    if config.webhook_enabled and not config.webhook_url:
        issues.append("Webhook URL is required when webhooks are enabled")
    
    return issues

# Environment-based configuration loader
def load_phase3_config_from_env() -> Phase3Config:
    """Load Phase 3 configuration from environment variables"""
    import os
    
    config = Phase3Config()
    
    # ML settings
    if os.getenv('WHALE_ML_ENABLED'):
        config.ml_model_enabled = os.getenv('WHALE_ML_ENABLED').lower() == 'true'
    if os.getenv('WHALE_ML_THRESHOLD'):
        config.ml_confidence_threshold = float(os.getenv('WHALE_ML_THRESHOLD'))
    if os.getenv('WHALE_ML_TRAINING_FREQ'):
        config.ml_training_frequency_hours = int(os.getenv('WHALE_ML_TRAINING_FREQ'))
    
    # Cross-chain settings
    if os.getenv('WHALE_CROSSCHAIN_ENABLED'):
        config.cross_chain_enabled = os.getenv('WHALE_CROSSCHAIN_ENABLED').lower() == 'true'
    if os.getenv('WHALE_COORDINATION_THRESHOLD'):
        config.coordination_score_threshold = float(os.getenv('WHALE_COORDINATION_THRESHOLD'))
    
    # Dashboard settings
    if os.getenv('WHALE_DASHBOARD_ENABLED'):
        config.dashboard_enabled = os.getenv('WHALE_DASHBOARD_ENABLED').lower() == 'true'
    if os.getenv('WHALE_DASHBOARD_PORT'):
        config.dashboard_port = int(os.getenv('WHALE_DASHBOARD_PORT'))
    
    # Alert settings
    if os.getenv('WHALE_ALERTS_ENABLED'):
        config.advanced_alerts_enabled = os.getenv('WHALE_ALERTS_ENABLED').lower() == 'true'
    if os.getenv('WHALE_ALERT_COOLDOWN'):
        config.alert_cooldown_seconds = int(os.getenv('WHALE_ALERT_COOLDOWN'))
    
    # Portfolio settings
    if os.getenv('WHALE_OPTIMIZATION_ENABLED'):
        config.portfolio_optimization_enabled = os.getenv('WHALE_OPTIMIZATION_ENABLED').lower() == 'true'
    if os.getenv('WHALE_MAX_POSITION'):
        config.max_position_allocation = float(os.getenv('WHALE_MAX_POSITION'))
    if os.getenv('WHALE_OPPORTUNITY_CONFIDENCE'):
        config.min_opportunity_confidence = float(os.getenv('WHALE_OPPORTUNITY_CONFIDENCE'))
    
    # Webhook settings
    if os.getenv('WHALE_WEBHOOK_URL'):
        config.webhook_url = os.getenv('WHALE_WEBHOOK_URL')
        config.webhook_enabled = True
    
    return config
