#!/usr/bin/env python3
"""
Configuration Module Example - Advanced Configuration Management

This example demonstrates how to configure and customize the whale bot
for different trading strategies and risk profiles.
"""

import os
from typing import Dict, List, Any, Optional
from dataclasses import dataclass

# Import configuration components
from hyperliquid_monitor_plus.config import (
    WhaleBotConfig, Phase3Config, get_aggressive_config, 
    get_conservative_config, get_demo_config, load_whale_bot_config_from_env,
    get_whale_addresses_from_env, validate_phase3_config
)

# Set up logging
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)


class ConfigurationDemo:
    """Demonstration of configuration management"""
    
    def basic_config_demo(self):
        """Demonstrate basic configuration options"""
        print("⚙️  Basic Configuration Options")
        print("=" * 50)
        
        # Conservative configuration
        conservative = get_conservative_config()
        print(f"🔒 CONSERVATIVE CONFIG:")
        print(f"   Max Whales: {conservative.max_whales}")
        print(f"   Alert Threshold: ${conservative.alert_threshold:,.2f}")
        print(f"   Conservative Mode: {conservative.conservative_mode}")
        print(f"   Risk Level: {conservative.risk_level}")
        
        # Aggressive configuration
        aggressive = get_aggressive_config()
        print(f"\n🚀 AGGRESSIVE CONFIG:")
        print(f"   Max Whales: {aggressive.max_whales}")
        print(f"   Alert Threshold: ${aggressive.alert_threshold:,.2f}")
        print(f"   Conservative Mode: {aggressive.conservative_mode}")
        print(f"   Risk Level: {aggressive.risk_level}")
        
        # Demo configuration
        demo = get_demo_config()
        print(f"\n🎭 DEMO CONFIG:")
        print(f"   Max Whales: {demo.max_whales}")
        print(f"   Alert Threshold: ${demo.alert_threshold:,.2f}")
        print(f"   Conservative Mode: {demo.conservative_mode}")
        print(f"   Risk Level: {demo.risk_level}")
        
        print("✅ Basic configuration demo completed!")
    
    def custom_config_demo(self):
        """Demonstrate custom configuration creation"""
        print("\n🏗️  Custom Configuration Creation")
        print("=" * 50)
        
        # Create custom configuration
        custom_config = WhaleBotConfig(
            min_whale_threshold=500_000,
            mega_whale_threshold=2_500_000,
            giant_whale_threshold=5_000_000,
            max_response_time_ms=300,
            processing_batch_size=25,
            follow_ratio=0.15,
            max_follow_ratio=0.3,
            leverage_cap=5.0,
            max_position_risk=0.015,
            max_daily_exposure=0.08,
            min_profit_threshold=0.003,
            max_slippage_threshold=0.008,
            max_market_impact_threshold=0.003,
            enable_real_time_alerts=True,
            enable_pattern_alerts=True,
            alert_cooldown_seconds=20,
            pattern_confidence_threshold=0.8,
            min_pattern_examples=5,
            enable_async_processing=True,
            max_concurrent_trades=15,
            cache_market_data_seconds=3
        )
        
        print("🎯 CUSTOM CONFIGURATION:")
        print(f"   Min Whale Threshold: ${custom_config.min_whale_threshold:,.2f}")
        print(f"   Mega Whale Threshold: ${custom_config.mega_whale_threshold:,.2f}")
        print(f"   Giant Whale Threshold: ${custom_config.giant_whale_threshold:,.2f}")
        print(f"   Follow Ratio: {custom_config.follow_ratio:.1%}")
        print(f"   Max Follow Ratio: {custom_config.max_follow_ratio:.1%}")
        print(f"   Pattern Confidence: {custom_config.pattern_confidence_threshold:.1%}")
        print(f"   Alert Cooldown: {custom_config.alert_cooldown_seconds}s")
        print(f"   Max Concurrent Trades: {custom_config.max_concurrent_trades}")
        print(f"   Async Processing: {custom_config.enable_async_processing}")
        print(f"   Real-time Alerts: {custom_config.enable_real_time_alerts}")
        
        # Configuration validation
        try:
            self._validate_custom_config(custom_config)
            print("   ✅ Configuration validation: PASSED")
        except Exception as e:
            print(f"   ❌ Configuration validation: FAILED - {e}")
        
        print("✅ Custom configuration demo completed!")
    
    def phase3_config_demo(self):
        """Demonstrate Phase 3 advanced configuration"""
        print("\n🚀 Phase 3 Advanced Configuration")
        print("=" * 50)
        
        # Create Phase 3 configuration
        phase3_config = Phase3Config(
            # ML Model Configuration
            ml_model_config={
                "whale_behavior_model": "v3.2.1",
                "market_regime_model": "v2.8.0", 
                "sentiment_model": "v1.9.5",
                "pattern_recognition_model": "v4.1.0",
                "auto_update": True,
                "confidence_threshold": 0.75
            },
            
            # Cross-Chain Configuration
            cross_chain_config={
                "enabled_chains": ["ethereum", "arbitrum", "polygon", "solana", "bsc"],
                "sync_frequency_seconds": 30,
                "min_value_threshold_usd": 100_000,
                "cross_chain_alerts": True
            },
            
            # Advanced Analytics
            analytics_config={
                "real_time_analysis": True,
                "correlation_tracking": True,
                "volatility_analysis": True,
                "sentiment_analysis": True,
                "behavioral_analysis": True,
                "predictive_modeling": True
            },
            
            # Portfolio Optimization
            portfolio_config={
                "auto_optimization": True,
                "risk_management": True,
                "position_sizing": True,
                "rebalancing_frequency": "daily",
                "max_position_risk": 0.05
            }
        )
        
        print("🤖 ML MODEL CONFIG:")
        for model, version in phase3_config.ml_model_config.items():
            if isinstance(version, bool):
                print(f"   {model}: {version}")
            elif model == "confidence_threshold":
                print(f"   {model}: {version:.2f}")
            else:
                print(f"   {model}: {version}")
        
        print(f"\n⛓️  CROSS-CHAIN CONFIG:")
        print(f"   Enabled Chains: {', '.join(phase3_config.cross_chain_config['enabled_chains'])}")
        print(f"   Sync Frequency: {phase3_config.cross_chain_config['sync_frequency_seconds']}s")
        print(f"   Min Value Threshold: ${phase3_config.cross_chain_config['min_value_threshold_usd']:,.2f}")
        print(f"   Cross-Chain Alerts: {phase3_config.cross_chain_config['cross_chain_alerts']}")
        
        print(f"\n📊 ANALYTICS CONFIG:")
        for feature, enabled in phase3_config.analytics_config.items():
            print(f"   {feature.replace('_', ' ').title()}: {enabled}")
        
        print(f"\n💼 PORTFOLIO CONFIG:")
        for setting, value in phase3_config.portfolio_config.items():
            print(f"   {setting.replace('_', ' ').title()}: {value}")
        
        # Validate Phase 3 configuration
        try:
            validation_result = validate_phase3_config(phase3_config)
            print(f"\n   ✅ Phase 3 Validation: {validation_result}")
        except Exception as e:
            print(f"\n   ❌ Phase 3 Validation: FAILED - {e}")
        
        print("✅ Phase 3 configuration demo completed!")
    
    def environment_config_demo(self):
        """Demonstrate environment variable configuration"""
        print("\n🌍 Environment Variable Configuration")
        print("=" * 50)
        
        # Simulate environment variables
        mock_env = {
            "WHALE_MONITOR_API_URL": "https://api.hyperliquid.xyz",
            "WHALE_MONITOR_WS_URL": "wss://ws.hyperliquid.xyz",
            "WHALE_MONITOR_MAX_WHALES": "20",
            "WHALE_MONITOR_ALERT_THRESHOLD": "250000",
            "WHALE_MONITOR_CONSERVATIVE_MODE": "false",
            "WHALE_MONITOR_DATABASE_PATH": "/data/whale_monitor.db",
            "WHALE_MONITOR_NOTIFICATION_CHANNELS": "telegram,discord,webhook",
            "WHALE_ADDRESSES": "0x010461C14e146ac35Fe42271BDC1134EE31C703a,0x8eb8a3b98659Cce290402893d0123abb75E3ab28"
        }
        
        print("🔧 ENVIRONMENT VARIABLES:")
        for key, value in mock_env.items():
            print(f"   {key}: {value}")
        
        # Load configuration from environment
        try:
            # Temporarily set environment variables
            original_env = {}
            for key, value in mock_env.items():
                original_env[key] = os.environ.get(key)
                os.environ[key] = value
            
            env_config = load_whale_bot_config_from_env()
            print(f"\n📋 LOADED FROM ENVIRONMENT:")
            print(f"   API URL: {env_config.api_url}")
            print(f"   WebSocket URL: {env_config.ws_url}")
            print(f"   Max Whales: {env_config.max_whales}")
            print(f"   Alert Threshold: ${env_config.alert_threshold:,.2f}")
            print(f"   Conservative Mode: {env_config.conservative_mode}")
            print(f"   Database Path: {env_config.database_path}")
            print(f"   Notification Channels: {', '.join(env_config.notification_channels)}")
            
            # Restore original environment
            for key, original_value in original_env.items():
                if original_value is None:
                    os.environ.pop(key, None)
                else:
                    os.environ[key] = original_value
            
            print("   ✅ Environment loading: SUCCESS")
            
        except Exception as e:
            print(f"   ❌ Environment loading: FAILED - {e}")
        
        print("✅ Environment configuration demo completed!")
    
    def config_comparison_demo(self):
        """Demonstrate configuration comparison and optimization"""
        print("\n📊 Configuration Comparison & Optimization")
        print("=" * 50)
        
        configs = {
            "Conservative": get_conservative_config(),
            "Balanced": get_demo_config(),
            "Aggressive": get_aggressive_config()
        }
        
        print("🔍 CONFIGURATION COMPARISON:")
        print(f"{'Setting':<25} {'Conservative':<15} {'Balanced':<15} {'Aggressive':<15}")
        print("-" * 70)
        
        print(f"{'Alert Threshold':<25} ${configs['Conservative'].alert_threshold:<14,.0f} ${configs['Balanced'].alert_threshold:<14,.0f} ${configs['Aggressive'].alert_threshold:<14,.0f}")
        print(f"{'Conservative Mode':<25} {str(configs['Conservative'].conservative_mode):<15} {str(configs['Balanced'].conservative_mode):<15} {str(configs['Aggressive'].conservative_mode):<15}")
        
        # Risk assessment
        print(f"\n⚠️  RISK ASSESSMENT:")
        print(f"   Conservative: LOW RISK - Safe for beginners, slower growth")
        print(f"   Balanced: MEDIUM RISK - Good balance of safety and opportunity")
        print(f"   Aggressive: HIGH RISK - Maximum opportunity, higher risk")
        
        print("✅ Configuration comparison completed!")
    
    def _validate_custom_config(self, config: WhaleBotConfig):
        """Validate custom configuration"""
        if config.min_whale_threshold <= 0:
            raise ValueError("Min whale threshold must be positive")
        
        if config.mega_whale_threshold <= config.min_whale_threshold:
            raise ValueError("Mega whale threshold must be greater than min whale threshold")
        
        if config.giant_whale_threshold <= config.mega_whale_threshold:
            raise ValueError("Giant whale threshold must be greater than mega whale threshold")
        
        if not 0 < config.follow_ratio <= 1:
            raise ValueError("Follow ratio must be between 0 and 1")
        
        if not 0 < config.max_follow_ratio <= 1:
            raise ValueError("Max follow ratio must be between 0 and 1")
        
        if config.pattern_confidence_threshold <= 0 or config.pattern_confidence_threshold > 1:
            raise ValueError("Pattern confidence threshold must be between 0 and 1")
        
        return True
    
    def _validate_ethereum_address(self, address: str) -> bool:
        """Validate Ethereum address format"""
        if not address or len(address) != 42:
            return False
        
        if not address.startswith('0x'):
            return False
        
        try:
            int(address, 16)
            return True
        except ValueError:
            return False
    
    def run_all_demos(self):
        """Run all configuration demonstrations"""
        print("🎯 HYPERLIQUID MONITOR PLUS - CONFIGURATION MODULE EXAMPLES")
        print("=" * 70)
        
        self.basic_config_demo()
        self.custom_config_demo()
        self.phase3_config_demo()
        self.environment_config_demo()
        self.config_comparison_demo()
        
        print("\n" + "=" * 70)
        print("🎉 All configuration demos completed successfully!")
        print("💡 Configuration capabilities demonstrated:")
        print("   ⚙️  Basic configuration options")
        print("   🏗️  Custom configuration creation")
        print("   🚀 Phase 3 advanced features")
        print("   🌍 Environment variable loading")
        print("   📊 Configuration comparison and optimization")


def validate_config(config: WhaleBotConfig) -> bool:
    """
    Validate whale bot configuration for consistency and safety.
    
    Args:
        config: WhaleBotConfig instance to validate
        
    Returns:
        bool: True if configuration is valid
        
    Raises:
        ValueError: If configuration has invalid parameters
    """
    # Use the internal validation method
    demo_instance = ConfigurationDemo()
    return demo_instance._validate_custom_config(config)


# Export a default configuration for testing and reference
config = WhaleBotConfig(
    min_whale_threshold=100_000,
    mega_whale_threshold=500_000,
    giant_whale_threshold=2_500_000,
    max_response_time_ms=500,
    processing_batch_size=20,
    follow_ratio=0.1,
    max_follow_ratio=0.25,
    leverage_cap=3.0,
    max_position_risk=0.01,
    max_daily_exposure=0.05,
    min_profit_threshold=0.002,
    max_slippage_threshold=0.005,
    max_market_impact_threshold=0.002,
    enable_real_time_alerts=True,
    enable_pattern_alerts=True,
    alert_cooldown_seconds=30,
    pattern_confidence_threshold=0.75,
    min_pattern_examples=3,
    enable_async_processing=True,
    max_concurrent_trades=10,
    cache_market_data_seconds=5
)


def configuration_best_practices():
    """Show configuration best practices"""
    print("\n📋 Configuration Best Practices")
    print("=" * 50)
    
    practices = [
        "🎯 Start with conservative mode for learning",
        "📈 Gradually increase thresholds as you gain experience", 
        "💾 Always backup your configuration files",
        "🔍 Regularly validate your whale addresses",
        "⚡ Monitor performance and adjust settings",
        "🛡️  Use environment variables for sensitive data",
        "📊 Track configuration changes over time",
        "🔄 Implement gradual rollouts for major changes"
    ]
    
    for practice in practices:
        print(f"   {practice}")


def main():
    """Main demonstration function"""
    
    # Run configuration demos
    config_demo = ConfigurationDemo()
    config_demo.run_all_demos()
    
    # Show best practices
    configuration_best_practices()


if __name__ == "__main__":
    main()