#!/usr/bin/env python3
"""
Core Module Example - Enhanced Whale Bot Configuration

This example demonstrates how to use the core whale bot functionality
including enhanced configuration, real-time detection, and intelligent following.
"""

import asyncio
import logging
from typing import List, Optional
from datetime import datetime

# Import core components
from hyperliquid_monitor_plus.core.core import WhaleBot, WhaleBotConfigEnhancement
from hyperliquid_monitor_plus.core_types import (
    WhaleTier, FollowAction, WhaleDetectionEvent, 
    WhaleDetectionCallback, MarketImpactCallback
)
from hyperliquid_monitor_plus.config import get_conservative_config

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


def whale_detection_callback(event: WhaleDetectionEvent) -> None:
    """Example callback for whale detection events"""
    logger.info(f"🐋 Whale detected! Tier: {event.whale_tier}, "
                f"Address: {event.address[:16]}..., "
                f"Amount: ${event.analysis.estimated_value:,.2f}")


def market_impact_callback(impact_data) -> None:
    """Example callback for market impact analysis"""
    logger.info(f"📊 Market Impact Analysis:")
    logger.info(f"   Volume Impact: {impact_data.volume_impact:.2f}%")
    logger.info(f"   Price Impact: {impact_data.price_impact:.2f}%")
    logger.info(f"   Confidence: {impact_data.confidence:.2f}")


async def basic_whale_bot_example():
    """Basic whale bot example with conservative settings"""
    print("🐋 Basic Whale Bot Example")
    print("=" * 50)
    
    # Load conservative configuration
    config = get_conservative_config()
    
    # Create whale bot with enhanced configuration
    bot_config = WhaleBotConfigEnhancement(
        enable_predictive_analysis=True,
        enable_ml_pattern_recognition=False,
        max_concurrent_whales=5,
        alert_cooldown_seconds=60
    )
    
    # Initialize whale bot
    whale_bot = WhaleBot(config, bot_config)
    
    # Set up callbacks
    whale_bot.whale_detection_callback = whale_detection_callback
    whale_bot.market_impact_callback = market_impact_callback
    
    print(f"✅ Whale Bot initialized with {config.max_whales} max whales")
    print(f"🎯 Conservative mode: {config.conservative_mode}")
    
    # Example whale addresses to monitor
    whale_addresses = [
        "0x010461C14e146ac35Fe42271BDC1134EE31C703a",
        "0x8eb8a3b98659Cce290402893d0123abb75E3ab28",
        "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"
    ]
    
    print(f"📍 Monitoring {len(whale_addresses)} whale addresses")
    for i, address in enumerate(whale_addresses):
        print(f"   {i+1}. {address[:16]}...")
    
    # Start monitoring (simulation)
    print("\n🚀 Starting whale monitoring...")
    print("   (This is a simulation - in production, this would connect to live data)")
    
    # Simulate some whale activity
    await simulate_whale_activity(whale_bot, whale_addresses)
    
    print("\n✅ Whale bot example completed!")


async def advanced_whale_bot_example():
    """Advanced whale bot with ML and predictive analysis"""
    print("\n🤖 Advanced Whale Bot with ML Features")
    print("=" * 50)
    
    # Load aggressive configuration
    config = get_conservative_config()
    
    # Enhanced configuration with ML features
    advanced_config = WhaleBotConfigEnhancement(
        enable_predictive_analysis=True,
        enable_ml_pattern_recognition=True,
        max_concurrent_whales=15,
        alert_cooldown_seconds=30,
        predictive_lookahead_hours=6,
        ml_confidence_threshold=0.75
    )
    
    # Initialize advanced whale bot
    whale_bot = WhaleBot(config, advanced_config)
    
    print(f"🤖 Advanced Whale Bot with ML capabilities")
    print(f"📈 Predictive analysis: {advanced_config.enable_predictive_analysis}")
    print(f"🧠 ML pattern recognition: {advanced_config.enable_ml_pattern_recognition}")
    print(f"⚡ Fast alerts: {advanced_config.alert_cooldown_seconds}s cooldown")
    
    # Set up enhanced callbacks
    whale_bot.whale_detection_callback = whale_detection_callback
    whale_bot.market_impact_callback = market_impact_callback
    
    # Add ML-specific callback
    def ml_pattern_callback(pattern_data):
        logger.info(f"🧠 ML Pattern Detected: {pattern_data['pattern_type']} "
                   f"(Confidence: {pattern_data['confidence']:.2f})")
    
    whale_bot.ml_pattern_callback = ml_pattern_callback
    
    print("\n🚀 Starting advanced whale monitoring...")
    await simulate_advanced_whale_activity(whale_bot)
    
    print("\n✅ Advanced whale bot example completed!")


async def multi_tier_whale_tracking():
    """Example of tracking whales across all tiers"""
    print("\n🎯 Multi-Tier Whale Tracking")
    print("=" * 50)
    
    config = get_conservative_config()
    bot_config = WhaleBotConfigEnhancement()
    
    whale_bot = WhaleBot(config, bot_config)
    
    # Define whale tiers and thresholds
    tier_thresholds = {
        WhaleTier.MINNOW: {"min_value": 100_000, "description": "$100K - $500K"},
        WhaleTier.SMALL: {"min_value": 500_000, "description": "$500K - $1M"},
        WhaleTier.MEDIUM: {"min_value": 1_000_000, "description": "$1M - $5M"},
        WhaleTier.LARGE: {"min_value": 5_000_000, "description": "$5M - $10M"},
        WhaleTier.GIANT: {"min_value": 10_000_000, "description": "$10M+"}
    }
    
    print("🏆 Whale Tier Classifications:")
    for tier, info in tier_thresholds.items():
        print(f"   {tier.value:8} - {info['description']}")
    
    # Simulate tracking across all tiers
    await simulate_multi_tier_tracking(whale_bot, tier_thresholds)
    
    print("\n✅ Multi-tier tracking example completed!")


async def simulate_whale_activity(bot, addresses: List[str]):
    """Simulate whale trading activity for demo purposes"""
    
    sample_trades = [
        {
            "address": addresses[0],
            "coin": "ETH",
            "side": "BUY",
            "size": 100.5,
            "price": 2500.00,
            "timestamp": datetime.now()
        },
        {
            "address": addresses[1], 
            "coin": "BTC",
            "side": "SELL",
            "size": 25.2,
            "price": 45000.00,
            "timestamp": datetime.now()
        }
    ]
    
    print("\n📊 Simulated Trading Activity:")
    for trade in sample_trades:
        print(f"   {trade['side']:4} {trade['size']:8.2f} {trade['coin']:6} "
              f"@ ${trade['price']:,.2f} by {trade['address'][:16]}...")
        
        # Simulate whale detection
        if trade['size'] > 50:  # Arbitrary threshold for demo
            event = WhaleDetectionEvent(
                address=trade['address'],
                trade_data=trade,
                whale_tier=WhaleTier.MEDIUM,
                analysis=None,  # Would be real analysis in production
                confidence=0.85
            )
            bot.whale_detection_callback(event)
    
    await asyncio.sleep(2)  # Brief pause for realism


async def simulate_advanced_whale_activity(bot):
    """Simulate advanced whale activity with ML patterns"""
    
    ml_patterns = [
        {"pattern_type": "Accumulation", "confidence": 0.87, "coins": ["ETH", "BTC"]},
        {"pattern_type": "Distribution", "confidence": 0.92, "coins": ["SOL", "AVAX"]},
        {"pattern_type": "Rotation", "confidence": 0.78, "coins": ["LINK", "UNI"]}
    ]
    
    print("\n🧠 ML Pattern Detection Simulation:")
    for pattern in ml_patterns:
        print(f"   Pattern: {pattern['pattern_type']:12} "
              f"(Confidence: {pattern['confidence']:.2f}) "
              f"Coins: {', '.join(pattern['coins'])}")
        
        # Simulate ML callback
        bot.ml_pattern_callback(pattern)
        
        await asyncio.sleep(0.5)


async def simulate_multi_tier_tracking(bot, tier_thresholds):
    """Simulate tracking whales across different tiers"""
    
    tier_examples = [
        {"tier": WhaleTier.MINNOW, "value": 250_000},
        {"tier": WhaleTier.SMALL, "value": 750_000},
        {"tier": WhaleTier.MEDIUM, "value": 2_500_000},
        {"tier": WhaleTier.LARGE, "value": 7_500_000},
        {"tier": WhaleTier.GIANT, "value": 15_000_000}
    ]
    
    print("\n🐋 Tier-Based Whale Detection:")
    for example in tier_examples:
        tier = example["tier"]
        value = example["value"]
        
        description = tier_thresholds[tier]["description"]
        print(f"   {tier.value:8} Whale: ${value:,.2f} ({description})")
        
        # Simulate detection event
        event = WhaleDetectionEvent(
            address="0x" + "a" * 40,  # Dummy address
            trade_data={"value": value},
            whale_tier=tier,
            analysis=None,
            confidence=0.90
        )
        bot.whale_detection_callback(event)
        
        await asyncio.sleep(0.3)


def configuration_examples():
    """Show different configuration options"""
    print("\n⚙️  Configuration Examples")
    print("=" * 50)
    
    # Conservative config
    conservative = get_conservative_config()
    print(f"🔒 Conservative Mode:")
    print(f"   Max Whales: {conservative.max_whales}")
    print(f"   Alert Threshold: {conservative.alert_threshold}")
    print(f"   Conservative: {conservative.conservative_mode}")
    
    # Aggressive config (if available)
    try:
        from hyperliquid_monitor_plus.config import get_aggressive_config
        aggressive = get_aggressive_config()
        print(f"\n🚀 Aggressive Mode:")
        print(f"   Max Whales: {aggressive.max_whales}")
        print(f"   Alert Threshold: {aggressive.alert_threshold}")
        print(f"   Conservative: {aggressive.conservative_mode}")
    except ImportError:
        print(f"\n⚠️  Aggressive config not available in this version")


async def main():
    """Run all core module examples"""
    print("🎯 HYPERLIQUID MONITOR PLUS - CORE MODULE EXAMPLES")
    print("=" * 70)
    
    # Show configuration options
    configuration_examples()
    
    # Run basic example
    await basic_whale_bot_example()
    
    # Run advanced example
    await advanced_whale_bot_example()
    
    # Run multi-tier tracking
    await multi_tier_whale_tracking()
    
    print("\n" + "=" * 70)
    print("🎉 All core module examples completed successfully!")
    print("💡 This demonstrates the enhanced whale bot capabilities")
    print("📚 For production use, configure with real API keys and endpoints")


if __name__ == "__main__":
    asyncio.run(main())