#!/usr/bin/env python3
"""
Analysis Module Example - Market Impact Analysis and Whale Classification

This example demonstrates how to use the analysis components for:
- Market impact analysis
- Whale size classification
- Volume anomaly detection
- Cross-asset correlation analysis
- Market regime detection
"""

import asyncio
import numpy as np
import pandas as pd
from datetime import datetime, timedelta
from typing import Dict, List, Tuple, Optional

# Import analysis components
from hyperliquid_monitor_plus.analysis import (
    MarketImpactAnalyzer, ImpactCalculation, SizeClassifier, 
    SizeClassification, VolumeAnomalyDetector, VolumeAnomaly,
    CorrelationEngine, CorrelationAnomaly, MarketRegime
)
from hyperliquid_monitor_plus.core_types import Trade, TradeSide
from hyperliquid_monitor_plus.monitor_types import Trade

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


class MarketAnalysisDemo:
    """Demonstration of market analysis capabilities"""
    
    def __init__(self):
        self.impact_analyzer = MarketImpactAnalyzer()
        self.size_classifier = SizeClassifier()
        self.volume_detector = VolumeAnomalyDetector()
        self.correlation_engine = CorrelationEngine()
        self.market_regime = MarketRegime()
    
    async def market_impact_analysis_demo(self):
        """Demonstrate market impact analysis"""
        print("📊 Market Impact Analysis Demo")
        print("=" * 50)
        
        # Sample whale trades
        sample_trades = [
            {
                "coin": "ETH",
                "size": 500.0,
                "price": 2450.00,
                "timestamp": datetime.now(),
                "coin_volume_24h": 100000000,
                "coin_market_cap": 3000000000
            },
            {
                "coin": "BTC",
                "size": 50.0,
                "price": 45000.00,
                "timestamp": datetime.now(),
                "coin_volume_24h": 2000000000,
                "coin_market_cap": 850000000000
            },
            {
                "coin": "SOL",
                "size": 10000.0,
                "price": 95.00,
                "timestamp": datetime.now(),
                "coin_volume_24h": 1500000000,
                "coin_market_cap": 45000000000
            }
        ]
        
        print("🔍 Analyzing market impact for whale trades:")
        
        for i, trade in enumerate(sample_trades, 1):
            print(f"\n   Trade {i}: {trade['size']:,.0f} {trade['coin']} @ ${trade['price']:,.2f}")
            
            # Calculate market impact
            impact = self.impact_analyzer.calculate_impact(
                size=trade["size"],
                price=trade["price"],
                coin_volume_24h=trade["coin_volume_24h"],
                market_cap=trade["coin_market_cap"]
            )
            
            print(f"   📈 Price Impact: {impact.price_impact:.2f}%")
            print(f"   📊 Volume Impact: {impact.volume_impact:.2f}%")
            print(f"   🎯 Confidence: {impact.confidence:.2f}")
            print(f"   ⚡ Impact Speed: {impact.impact_speed}")
        
        print("✅ Market impact analysis completed!")
    
    async def whale_classification_demo(self):
        """Demonstrate whale size classification"""
        print("\n🐋 Whale Size Classification Demo")
        print("=" * 50)
        
        # Define size thresholds (USD)
        thresholds = {
            "minnow": 100_000,
            "small": 500_000,
            "medium": 1_000_000,
            "large": 5_000_000,
            "giant": 10_000_000
        }
        
        sample_sizes = [
            75_000,    # Below threshold
            250_000,   # Minnow
            750_000,   # Small
            2_500_000, # Medium
            8_000_000, # Large
            15_000_000 # Giant
        ]
        
        print("🏆 Whale Classification Tiers:")
        for tier, threshold in thresholds.items():
            print(f"   {tier.upper():8}: ${threshold:>10,}")
        
        print(f"\n🔍 Classifying {len(sample_sizes)} trade sizes:")
        
        for size in sample_sizes:
            classification = self.size_classifier.classify_whale_size(size)
            
            tier_emoji = {
                "minnow": "🐟",
                "small": "🐬", 
                "medium": "🦈",
                "large": "🐋",
                "giant": "👑"
            }
            
            emoji = tier_emoji.get(classification.tier, "❓")
            print(f"   ${size:>10,} → {emoji} {classification.tier.upper():8} "
                  f"(Confidence: {classification.confidence:.2f})")
        
        print("✅ Whale classification completed!")
    
    async def volume_anomaly_detection_demo(self):
        """Demonstrate volume anomaly detection"""
        print("\n📈 Volume Anomaly Detection Demo")
        print("=" * 50)
        
        # Generate sample volume data with anomalies
        coins = ["ETH", "BTC", "SOL", "AVAX", "LINK"]
        
        print("🔍 Detecting volume anomalies:")
        
        for coin in coins:
            # Simulate 30 days of volume data with occasional spikes
            base_volume = 50000000 + hash(coin) % 50000000
            volumes = np.random.normal(base_volume, base_volume * 0.2, 30)
            
            # Add some anomalous spikes
            if hash(coin) % 3 == 0:  # 33% chance of anomaly
                spike_day = np.random.randint(5, 25)
                volumes[spike_day] = base_volume * (2 + np.random.random() * 3)
            
            # Detect anomalies
            anomalies = self.volume_detector.detect_anomalies(volumes)
            
            print(f"\n   📊 {coin} Volume Analysis:")
            print(f"      Base Volume: ${base_volume:,.0f}")
            print(f"      Mean Volume: ${np.mean(volumes):,.0f}")
            print(f"      Std Deviation: ${np.std(volumes):,.0f}")
            print(f"      Anomalies Found: {len(anomalies)}")
            
            for anomaly in anomalies:
                spike_multiplier = anomaly.volume / base_volume
                print(f"      🚨 Anomaly: Day {anomaly.day} - "
                      f"${anomaly.volume:,.0f} ({spike_multiplier:.1f}x normal)")
        
        print("✅ Volume anomaly detection completed!")
    
    async def correlation_analysis_demo(self):
        """Demonstrate cross-asset correlation analysis"""
        print("\n🔗 Cross-Asset Correlation Analysis")
        print("=" * 50)
        
        coins = ["BTC", "ETH", "SOL", "AVAX", "LINK"]
        
        print("🔍 Calculating price correlations:")
        
        # Generate sample price data
        price_data = {}
        for coin in coins:
            # Simulate correlated price movements
            base_price = 1000 + hash(coin) % 50000
            days = 30
            
            # BTC leads the market
            btc_returns = np.random.normal(0, 0.05, days)
            if coin == "BTC":
                prices = [base_price]
            else:
                # Other coins are correlated with BTC
                correlation = 0.7 if coin in ["ETH", "SOL"] else 0.5
                coin_returns = (correlation * btc_returns + 
                               (1-correlation) * np.random.normal(0, 0.03, days))
                prices = [base_price * (1 + np.prod(1 + coin_returns[:i])) for i in range(1, days+1)]
            
            price_data[coin] = prices
        
        # Calculate correlations
        correlations = self.correlation_engine.calculate_correlations(price_data)
        
        print(f"\n📊 Price Correlations (30-day):")
        for i, coin1 in enumerate(coins):
            for j, coin2 in enumerate(coins[i+1:], i+1):
                corr = correlations.get((coin1, coin2), 0)
                strength = "Strong" if abs(corr) > 0.7 else "Moderate" if abs(corr) > 0.4 else "Weak"
                direction = "Positive" if corr > 0 else "Negative"
                print(f"   {coin1:4} ↔ {coin2:4}: {corr:6.3f} ({strength} {direction})")
        
        # Detect correlation anomalies
        print(f"\n🚨 Correlation Anomalies:")
        anomalies = self.correlation_engine.detect_correlation_anomalies(correlations)
        for anomaly in anomalies:
            print(f"   {anomaly.coin1} ↔ {anomaly.coin2}: "
                  f"{anomaly.current_correlation:.3f} "
                  f"(Δ {anomaly.deviation:+.3f})")
        
        print("✅ Correlation analysis completed!")
    
    async def market_regime_detection_demo(self):
        """Demonstrate market regime detection"""
        print("\n🎭 Market Regime Detection Demo")
        print("=" * 50)
        
        # Simulate different market regimes
        regimes = [
            {"name": "Bull Market", "volatility": 0.03, "trend": 0.02, "volume": 1.5},
            {"name": "Bear Market", "volatility": 0.06, "trend": -0.03, "volume": 0.8},
            {"name": "Sideways Market", "volatility": 0.025, "trend": 0.001, "volume": 1.0},
            {"name": "High Volatility", "volatility": 0.08, "trend": 0.01, "volume": 1.8},
            {"name": "Low Activity", "volatility": 0.015, "trend": -0.005, "volume": 0.5}
        ]
        
        print("🔍 Detecting market regimes:")
        
        for regime_data in regimes:
            regime = self.market_regime.detect_regime(
                volatility=regime_data["volatility"],
                trend=regime_data["trend"],
                volume_ratio=regime_data["volume"]
            )
            
            emoji = {
                "Bull": "🐂",
                "Bear": "🐻", 
                "Sideways": "➡️",
                "High Volatility": "⚡",
                "Low Activity": "😴"
            }.get(regime.name.split()[0], "❓")
            
            print(f"\n   {emoji} Regime: {regime.name}")
            print(f"      Volatility: {regime_data['volatility']:.3f}")
            print(f"      Trend: {regime_data['trend']:+.3f}")
            print(f"      Volume Ratio: {regime_data['volume']:.1f}")
            print(f"      Confidence: {regime.confidence:.2f}")
            print(f"      Characteristics: {regime.characteristics}")
        
        print("✅ Market regime detection completed!")
    
    async def comprehensive_analysis_demo(self):
        """Demonstrate comprehensive market analysis"""
        print("\n🎯 Comprehensive Market Analysis")
        print("=" * 50)
        
        # Real-time market snapshot
        market_snapshot = {
            "BTC": {"price": 45000, "volume_24h": 2.5e9, "volatility": 0.04},
            "ETH": {"price": 2500, "volume_24h": 1.2e9, "volatility": 0.05},
            "SOL": {"price": 95, "volume_24h": 800e6, "volatility": 0.06}
        }
        
        print("📊 Real-time Market Analysis:")
        
        for coin, data in market_snapshot.items():
            print(f"\n   {coin} Analysis:")
            
            # Market impact
            impact = self.impact_analyzer.calculate_impact(
                size=1000000 / data["price"],  # $1M trade
                price=data["price"],
                coin_volume_24h=data["volume_24h"],
                market_cap=data["price"] * 19000000  # Approximate
            )
            
            # Size classification
            classification = self.size_classifier.classify_whale_size(1000000)
            
            # Regime detection
            regime = self.market_regime.detect_regime(
                volatility=data["volatility"],
                trend=0.002,  # Slight positive trend
                volume_ratio=1.2
            )
            
            print(f"      💰 Price: ${data['price']:,.2f}")
            print(f"      📈 Volatility: {data['volatility']:.1%}")
            print(f"      📊 24h Volume: ${data['volume_24h']:,.0f}")
            print(f"      🎯 Impact (1M trade): {impact.price_impact:.2f}%")
            print(f"      🐋 Whale Class: {classification.tier.upper()}")
            print(f"      🎭 Market Regime: {regime.name}")
            print(f"      ✅ Analysis Confidence: {regime.confidence:.2f}")
        
        print("✅ Comprehensive analysis completed!")
    
    async def run_all_demos(self):
        """Run all analysis demonstrations"""
        print("🎯 HYPERLIQUID MONITOR PLUS - ANALYSIS MODULE EXAMPLES")
        print("=" * 70)
        
        await self.market_impact_analysis_demo()
        await self.whale_classification_demo()
        await self.volume_anomaly_detection_demo()
        await self.correlation_analysis_demo()
        await self.market_regime_detection_demo()
        await self.comprehensive_analysis_demo()
        
        print("\n" + "=" * 70)
        print("🎉 All analysis demos completed successfully!")
        print("💡 Analysis capabilities demonstrated:")
        print("   📊 Market impact calculation")
        print("   🐋 Whale size classification")
        print("   📈 Volume anomaly detection")
        print("   🔗 Cross-asset correlation")
        print("   🎭 Market regime detection")
        print("   🎯 Comprehensive market analysis")


def data_simulation_utils():
    """Utility functions for data simulation"""
    def generate_sample_trades(num_trades=100):
        """Generate sample trades for analysis"""
        trades = []
        coins = ["BTC", "ETH", "SOL", "AVAX", "LINK"]
        
        for i in range(num_trades):
            trade = {
                "coin": np.random.choice(coins),
                "size": np.random.exponential(1000),
                "price": 1000 + np.random.exponential(40000),
                "timestamp": datetime.now() - timedelta(hours=i),
                "side": np.random.choice(["BUY", "SELL"])
            }
            trades.append(trade)
        
        return trades
    
    def calculate_market_metrics(trades):
        """Calculate basic market metrics"""
        df = pd.DataFrame(trades)
        df['value'] = df['size'] * df['price']
        
        return {
            'total_volume': df['value'].sum(),
            'avg_trade_size': df['size'].mean(),
            'num_trades': len(df),
            'dominant_side': df['side'].mode()[0] if len(df) > 0 else None
        }


async def main():
    """Main demonstration function"""
    
    # Run analysis demos
    analysis_demo = MarketAnalysisDemo()
    await analysis_demo.run_all_demos()
    
    # Show data utilities
    print("\n🛠️  Data Simulation Utilities")
    print("=" * 50)
    
    sample_trades = data_simulation_utils().generate_sample_trades(20)
    metrics = data_simulation_utils().calculate_market_metrics(sample_trades)
    
    print("📊 Sample Data Generation:")
    print(f"   Generated {len(sample_trades)} sample trades")
    print(f"   Total Volume: ${metrics['total_volume']:,.2f}")
    print(f"   Average Trade Size: {metrics['avg_trade_size']:.2f}")
    print(f"   Dominant Side: {metrics['dominant_side']}")


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