"""
Whale Bot Configuration - Environment and settings management

This module provides configuration management for the whale bot with environment
variable support and flexible settings for different use cases.
"""

import os
import logging
from typing import List, Optional
from dataclasses import dataclass

from ..core_types import WhaleBotConfig, WhaleTier, TradeUrgency, FollowAction

logger = logging.getLogger(__name__)

# Default whale bot configuration
DEFAULT_WHALE_BOT_CONFIG = WhaleBotConfig(
    # Size thresholds (USD)
    min_whale_threshold=1_000_000,     # $1M minimum for whale detection
    mega_whale_threshold=5_000_000,    # $5M for mega alerts  
    giant_whale_threshold=10_000_000,  # $10M for giant alerts
    
    # Speed requirements
    max_response_time_ms=500,          # Maximum response time in milliseconds
    processing_batch_size=50,          # Number of trades to process in batch
    
    # Follow parameters
    follow_ratio=0.1,                  # Follow with 10% of whale size by default
    max_follow_ratio=0.5,              # Never follow with more than 50% of whale size
    leverage_cap=10.0,                 # Maximum leverage for following
    
    # Risk management
    max_position_risk=0.02,            # Max 2% of portfolio per trade
    max_daily_exposure=0.10,           # Max 10% of portfolio exposure per day
    min_profit_threshold=0.005,        # Min 0.5% profit before considering follow
    
    # Market impact thresholds
    max_slippage_threshold=0.01,       # Max 1% slippage acceptable
    max_market_impact_threshold=0.005, # Max 0.5% market impact
    
    # Alert settings
    enable_real_time_alerts=True,
    enable_pattern_alerts=True,
    alert_cooldown_seconds=30,         # Cool down between alerts
    
    # Pattern recognition settings
    pattern_confidence_threshold=0.7,  # Minimum confidence for pattern detection
    min_pattern_examples=3,            # Minimum historical examples for pattern
    
    # Performance optimization
    enable_async_processing=True,
    max_concurrent_trades=10,
    cache_market_data_seconds=5        # Cache market data for this duration
)

def load_whale_bot_config_from_env() -> WhaleBotConfig:
    """
    Load whale bot configuration from environment variables.
    
    Environment variables:
    - WHALE_BOT_MIN_THRESHOLD: Minimum whale size in USD
    - WHALE_BOT_MEGA_THRESHOLD: Mega whale size in USD
    - WHALE_BOT_GIANT_THRESHOLD: Giant whale size in USD
    - WHALE_BOT_MAX_RESPONSE_MS: Maximum response time in milliseconds
    - WHALE_BOT_FOLLOW_RATIO: Default follow ratio (0.0-1.0)
    - WHALE_BOT_MAX_FOLLOW_RATIO: Maximum follow ratio (0.0-1.0)
    - WHALE_BOT_LEVERAGE_CAP: Maximum leverage
    - WHALE_BOT_MAX_POSITION_RISK: Maximum position risk (0.0-1.0)
    - WHALE_BOT_MAX_DAILY_EXPOSURE: Maximum daily exposure (0.0-1.0)
    - WHALE_BOT_MIN_PROFIT_THRESHOLD: Minimum profit threshold (0.0-1.0)
    - WHALE_BOT_MAX_SLIPPAGE: Maximum slippage threshold (0.0-1.0)
    - WHALE_BOT_MAX_IMPACT: Maximum market impact threshold (0.0-1.0)
    - WHALE_BOT_ALERT_COOLDOWN: Alert cooldown in seconds
    - WHALE_BOT_PATTERN_CONFIDENCE: Pattern confidence threshold (0.0-1.0)
    - WHALE_BOT_MIN_PATTERN_EXAMPLES: Minimum pattern examples
    - WHALE_BOT_MAX_CONCURRENT: Maximum concurrent trades
    - WHALE_BOT_CACHE_SECONDS: Market data cache duration in seconds
    
    Returns:
        WhaleBotConfig: Configuration loaded from environment
    """
    config = DEFAULT_WHALE_BOT_CONFIG
    
    # Size thresholds
    if whale_threshold := os.getenv('WHALE_BOT_MIN_THRESHOLD'):
        try:
            config.min_whale_threshold = float(whale_threshold)
        except ValueError:
            pass
    
    if mega_threshold := os.getenv('WHALE_BOT_MEGA_THRESHOLD'):
        try:
            config.mega_whale_threshold = float(mega_threshold)
        except ValueError:
            pass
    
    if giant_threshold := os.getenv('WHALE_BOT_GIANT_THRESHOLD'):
        try:
            config.giant_whale_threshold = float(giant_threshold)
        except ValueError:
            pass
    
    # Speed settings
    if max_response := os.getenv('WHALE_BOT_MAX_RESPONSE_MS'):
        try:
            config.max_response_time_ms = int(max_response)
        except ValueError:
            pass
    
    if batch_size := os.getenv('WHALE_BOT_BATCH_SIZE'):
        try:
            config.processing_batch_size = int(batch_size)
        except ValueError:
            pass
    
    # Follow parameters
    if follow_ratio := os.getenv('WHALE_BOT_FOLLOW_RATIO'):
        try:
            config.follow_ratio = float(follow_ratio)
        except ValueError:
            pass
    
    if max_follow_ratio := os.getenv('WHALE_BOT_MAX_FOLLOW_RATIO'):
        try:
            config.max_follow_ratio = float(max_follow_ratio)
        except ValueError:
            pass
    
    if leverage_cap := os.getenv('WHALE_BOT_LEVERAGE_CAP'):
        try:
            config.leverage_cap = float(leverage_cap)
        except ValueError:
            pass
    
    # Risk management
    if max_risk := os.getenv('WHALE_BOT_MAX_POSITION_RISK'):
        try:
            config.max_position_risk = float(max_risk)
        except ValueError:
            pass
    
    if max_exposure := os.getenv('WHALE_BOT_MAX_DAILY_EXPOSURE'):
        try:
            config.max_daily_exposure = float(max_exposure)
        except ValueError:
            pass
    
    if min_profit := os.getenv('WHALE_BOT_MIN_PROFIT_THRESHOLD'):
        try:
            config.min_profit_threshold = float(min_profit)
        except ValueError:
            pass
    
    # Market impact thresholds
    if max_slippage := os.getenv('WHALE_BOT_MAX_SLIPPAGE'):
        try:
            config.max_slippage_threshold = float(max_slippage)
        except ValueError:
            pass
    
    if max_impact := os.getenv('WHALE_BOT_MAX_IMPACT'):
        try:
            config.max_market_impact_threshold = float(max_impact)
        except ValueError:
            pass
    
    # Alert settings
    if cooldown := os.getenv('WHALE_BOT_ALERT_COOLDOWN'):
        try:
            config.alert_cooldown_seconds = int(cooldown)
        except ValueError:
            pass
    
    # Pattern recognition
    if pattern_conf := os.getenv('WHALE_BOT_PATTERN_CONFIDENCE'):
        try:
            config.pattern_confidence_threshold = float(pattern_conf)
        except ValueError:
            pass
    
    if min_examples := os.getenv('WHALE_BOT_MIN_PATTERN_EXAMPLES'):
        try:
            config.min_pattern_examples = int(min_examples)
        except ValueError:
            pass
    
    # Performance settings
    if max_concurrent := os.getenv('WHALE_BOT_MAX_CONCURRENT'):
        try:
            config.max_concurrent_trades = int(max_concurrent)
        except ValueError:
            pass
    
    if cache_seconds := os.getenv('WHALE_BOT_CACHE_SECONDS'):
        try:
            config.cache_market_data_seconds = int(cache_seconds)
        except ValueError:
            pass
    
    return config

def get_aggressive_config() -> WhaleBotConfig:
    """
    Get aggressive trading configuration for high-frequency whale following.
    
    Returns:
        WhaleBotConfig: Aggressive settings optimized for speed and opportunity
    """
    config = DEFAULT_WHALE_BOT_CONFIG
    
    # Lower thresholds to catch more opportunities
    config.min_whale_threshold = 500_000     # $500K minimum
    config.mega_whale_threshold = 2_000_000  # $2M for mega
    config.giant_whale_threshold = 5_000_000 # $5M for giant
    
    # Faster response
    config.max_response_time_ms = 200        # 200ms max
    config.alert_cooldown_seconds = 10       # 10 second cooldown
    
    # Aggressive following
    config.follow_ratio = 0.15               # 15% follow ratio
    config.max_follow_ratio = 0.6            # Up to 60%
    
    # Higher risk tolerance
    config.max_position_risk = 0.03          # 3% per trade
    config.max_daily_exposure = 0.15         # 15% daily exposure
    config.max_slippage_threshold = 0.015    # 1.5% slippage ok
    config.max_market_impact_threshold = 0.008 # 0.8% impact ok
    
    return config

def get_conservative_config() -> WhaleBotConfig:
    """
    Get conservative trading configuration for risk-averse whale following.
    
    Returns:
        WhaleBotConfig: Conservative settings optimized for safety and quality
    """
    config = DEFAULT_WHALE_BOT_CONFIG
    
    # Higher thresholds for higher quality trades
    config.min_whale_threshold = 2_000_000   # $2M minimum
    config.mega_whale_threshold = 10_000_000 # $10M for mega
    config.giant_whale_threshold = 20_000_000 # $20M for giant
    
    # Slower, more careful response
    config.max_response_time_ms = 1000       # 1 second max
    config.alert_cooldown_seconds = 60       # 1 minute cooldown
    
    # Conservative following
    config.follow_ratio = 0.05               # 5% follow ratio
    config.max_follow_ratio = 0.3            # Up to 30%
    
    # Lower risk tolerance
    config.max_position_risk = 0.01          # 1% per trade
    config.max_daily_exposure = 0.05         # 5% daily exposure
    config.max_slippage_threshold = 0.005    # 0.5% slippage max
    config.max_market_impact_threshold = 0.003 # 0.3% impact max
    
    # Higher pattern confidence
    config.pattern_confidence_threshold = 0.8 # 80% confidence needed
    config.min_pattern_examples = 5          # 5 examples minimum
    
    return config

def get_demo_config() -> WhaleBotConfig:
    """
    Get demo configuration for testing and development.
    
    Returns:
        WhaleBotConfig: Demo settings with low thresholds
    """
    config = DEFAULT_WHALE_BOT_CONFIG
    
    # Very low thresholds for demo
    config.min_whale_threshold = 50_000      # $50K for demo
    config.mega_whale_threshold = 200_000    # $200K for mega demo
    config.giant_whale_threshold = 500_000   # $500K for giant demo
    
    # Slower for demo/testing
    config.max_response_time_ms = 2000       # 2 seconds for demo
    config.alert_cooldown_seconds = 5        # 5 second cooldown
    
    # Small following for demo
    config.follow_ratio = 0.02               # 2% follow ratio
    config.max_follow_ratio = 0.1            # Up to 10%
    
    # Conservative risk for demo
    config.max_position_risk = 0.005         # 0.5% per trade
    config.max_daily_exposure = 0.02         # 2% daily exposure
    
    # Demo-friendly thresholds
    config.max_slippage_threshold = 0.02     # 2% slippage ok
    config.max_market_impact_threshold = 0.01 # 1% impact ok
    
    return config

def get_whale_addresses_from_env() -> List[str]:
    """
    Get whale addresses from environment variable.
    
    Environment variable: WHALE_ADDRESSES (comma-separated)
    
    Returns:
        List[str]: List of whale addresses
    """
    addresses_str = os.getenv('WHALE_ADDRESSES', '')
    
    if not addresses_str:
        return []
    
    addresses = [addr.strip() for addr in addresses_str.split(',') if addr.strip()]
    
    # Validate address format (basic check)
    valid_addresses = []
    for addr in addresses:
        if addr.startswith('0x') and len(addr) == 42:
            valid_addresses.append(addr)
        else:
            print(f"Warning: Invalid address format: {addr}")
    
    return valid_addresses

# Example environment variable template
ENVIRONMENT_VARIABLES_TEMPLATE = """
# Whale Bot Environment Configuration Template
# Copy this to your .env file and customize values

# ===== WHALE TRACKING CONFIGURATION =====
# Minimum whale size thresholds (USD)
WHALE_BOT_MIN_THRESHOLD=1000000
WHALE_BOT_MEGA_THRESHOLD=5000000
WHALE_BOT_GIANT_THRESHOLD=10000000

# Performance settings
WHALE_BOT_MAX_RESPONSE_MS=500
WHALE_BOT_BATCH_SIZE=50

# Following parameters
WHALE_BOT_FOLLOW_RATIO=0.1
WHALE_BOT_MAX_FOLLOW_RATIO=0.5
WHALE_BOT_LEVERAGE_CAP=10.0

# Risk management
WHALE_BOT_MAX_POSITION_RISK=0.02
WHALE_BOT_MAX_DAILY_EXPOSURE=0.10
WHALE_BOT_MIN_PROFIT_THRESHOLD=0.005

# Market impact thresholds
WHALE_BOT_MAX_SLIPPAGE=0.01
WHALE_BOT_MAX_IMPACT=0.005

# Alert settings
WHALE_BOT_ALERT_COOLDOWN=30

# Pattern recognition
WHALE_BOT_PATTERN_CONFIDENCE=0.7
WHALE_BOT_MIN_PATTERN_EXAMPLES=3

# Performance optimization
WHALE_BOT_MAX_CONCURRENT=10
WHALE_BOT_CACHE_SECONDS=5

# ===== WHALE ADDRESSES =====
# Comma-separated list of whale addresses to monitor
WHALE_ADDRESSES=0x1234567890123456789012345678901234567890,0xabcdefabcdefabcdefabcdefabcdefabcdefabcd

# ===== DATABASE SETTINGS =====
# Database path for storing whale trades
DB_PATH=whale_trading.db

# ===== NOTIFICATION SETTINGS =====
# Telegram bot settings (optional)
TELEGRAM_BOT_TOKEN=your_bot_token_here
TELEGRAM_CHAT_ID=your_chat_id_here

# Discord webhook settings (optional) 
DISCORD_WEBHOOK_URL=your_webhook_url_here
"""

def print_config_example():
    """Print example configuration for reference"""
    print("🐋 Whale Bot Configuration Example")
    print("=" * 50)
    print(ENVIRONMENT_VARIABLES_TEMPLATE)


class Config:
    """
    High-level configuration manager
    Provides centralized configuration management
    """
    
    def __init__(self, config_type: str = "default"):
        """
        Initialize configuration manager
        
        Args:
            config_type: Type of configuration to load ("default", "aggressive", "conservative", "demo")
        """
        if config_type == "aggressive":
            self.whale_config = get_aggressive_config()
        elif config_type == "conservative":
            self.whale_config = get_conservative_config()
        elif config_type == "demo":
            self.whale_config = get_demo_config()
        else:
            self.whale_config = load_whale_bot_config_from_env()
        
        self.config_type = config_type
        logger.info(f"Config initialized with type: {config_type}")
    
    def get_whale_config(self) -> WhaleBotConfig:
        """Get whale bot configuration"""
        return self.whale_config
    
    def update_config(self, **kwargs):
        """Update configuration parameters"""
        for key, value in kwargs.items():
            if hasattr(self.whale_config, key):
                setattr(self.whale_config, key, value)
                logger.info(f"Updated {key} to {value}")
    
    def print_config(self):
        """Print current configuration"""
        print(f"Current Configuration ({self.config_type}):")
        print(self.whale_config)