#!/usr/bin/env python3
"""
Visualization Example - Comprehensive Chart and Dashboard Demo

This example demonstrates the visualization capabilities of hyperliquid-monitor-plus
including:
- Whale volume charts
- Market impact analysis
- Portfolio performance tracking
- Real-time dashboards
- Export capabilities

Author: Pezhman Hajipour
Version: 3.0.0
"""

import asyncio
import random
from datetime import datetime, timedelta
from typing import List
import json

# Import visualization components
try:
    from hyperliquid_monitor_plus.visualization import (
        WhaleVolumeChart, MarketImpactPlot, TradeDistributionChart,
        PortfolioPerformanceChart, SentimentAnalysisPlot, CorrelationHeatmap,
        RealTimeWhaleTracker, TradingMetricsWidget, AlertDistributionWidget,
        PerformanceDashboard, RealTimeChart, ChartExporter, HTMLReportGenerator,
        check_visualization_support, get_recommended_installation
    )
    from hyperliquid_monitor_plus.visualization.plots import WhaleDataPoint
    VIZ_AVAILABLE = True
except ImportError as e:
    print(f"❌ Visualization libraries not available: {e}")
    print(f"💡 Install with: pip install hyperliquid-monitor-plus[viz]")
    VIZ_AVAILABLE = False

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

class VisualizationDemo:
    """Comprehensive visualization demonstration"""
    
    def __init__(self):
        self.demo_data = self._generate_demo_data()
        self.exporter = ChartExporter() if VIZ_AVAILABLE else None
        
    def _generate_demo_data(self) -> List[WhaleDataPoint]:
        """Generate realistic demo whale trading data"""
        symbols = ['BTC', 'ETH', 'SOL', 'ARB', 'OP', 'AVAX', 'MATIC', 'LINK']
        whale_tiers = ['Minnow', 'Dolphin', 'Whale', 'Mega Whale', 'Giant Whale']
        
        demo_data = []
        base_time = datetime.now() - timedelta(hours=24)
        
        for i in range(100):  # Generate 100 demo trades
            # Random time within last 24 hours
            trade_time = base_time + timedelta(minutes=random.randint(0, 1440))
            
            # Random symbol and tier
            symbol = random.choice(symbols)
            whale_tier = random.choice(whale_tiers)
            
            # Generate realistic volumes based on tier
            tier_multipliers = {
                'Minnow': (1000, 10000),
                'Dolphin': (10000, 100000), 
                'Whale': (100000, 1000000),
                'Mega Whale': (1000000, 10000000),
                'Giant Whale': (10000000, 100000000)
            }
            
            min_vol, max_vol = tier_multipliers[whale_tier]
            volume = random.uniform(min_vol, max_vol)
            
            # Generate price (realistic crypto prices)
            base_prices = {'BTC': 45000, 'ETH': 3000, 'SOL': 100, 'ARB': 1.5, 
                          'OP': 2.5, 'AVAX': 40, 'MATIC': 0.8, 'LINK': 15}
            price = base_prices[symbol] * random.uniform(0.95, 1.05)
            
            # Random side
            side = random.choice(['BUY', 'SELL'])
            
            # Random whale address
            address = f"0x{''.join(random.choices('0123456789abcdef', k=40))}"
            
            data_point = WhaleDataPoint(
                timestamp=trade_time,
                address=address,
                symbol=symbol,
                side=side,
                size=volume / price,  # Calculate size from volume and price
                price=price,
                volume_usd=volume,
                whale_tier=whale_tier
            )
            
            demo_data.append(data_point)
            
        return sorted(demo_data, key=lambda x: x.timestamp)
        
    def demo_whale_volume_chart(self):
        """Demonstrate whale volume tracking chart"""
        print("📊 Creating Whale Volume Chart...")
        
        chart = WhaleVolumeChart(figsize=(14, 8))
        
        # Add demo data
        for data_point in self.demo_data[:50]:  # Use first 50 points
            chart.add_data_point(data_point)
            
        try:
            # Create matplotlib chart
            fig = chart.plot_matplotlib("demo_whale_volume.png")
            print("✅ Matplotlib chart saved to demo_whale_volume.png")
            
            # Create plotly chart
            fig = chart.plot_plotly("demo_whale_volume.html", interactive=True)
            print("✅ Plotly chart saved to demo_whale_volume.html")
            
        except ImportError as e:
            print(f"❌ Chart creation failed: {e}")
            print(f"💡 Install visualization libraries: {get_recommended_installation()}")
            
    def demo_market_impact_analysis(self):
        """Demonstrate market impact analysis"""
        print("📈 Creating Market Impact Analysis...")
        
        impact_plot = MarketImpactPlot(figsize=(16, 10))
        
        # Generate market impact data
        symbols = ['BTC', 'ETH', 'SOL', 'ARB']
        base_prices = {'BTC': 45000, 'ETH': 3000, 'SOL': 100, 'ARB': 1.5}
        
        for _ in range(30):
            symbol = random.choice(symbols)
            base_price = base_prices[symbol]
            
            # Generate realistic impact data
            trade_size = random.uniform(100000, 10000000)
            price_change = random.uniform(-0.05, 0.05)  # ±5% max
            price_before = base_price
            price_after = base_price * (1 + price_change)
            volume = trade_size
            
            impact_plot.add_impact_data(
                symbol=symbol,
                trade_size=trade_size,
                price_before=price_before,
                price_after=price_after,
                volume=volume,
                timestamp=datetime.now() - timedelta(hours=random.randint(0, 24))
            )
            
        try:
            # Create matplotlib analysis
            fig = impact_plot.plot_matplotlib("demo_market_impact.png")
            print("✅ Market impact chart saved to demo_market_impact.png")
            
            # Create plotly analysis  
            fig = impact_plot.plot_plotly("demo_market_impact.html")
            print("✅ Interactive market impact chart saved to demo_market_impact.html")
            
        except ImportError as e:
            print(f"❌ Market impact analysis failed: {e}")
            
    def demo_portfolio_performance(self):
        """Demonstrate portfolio performance tracking"""
        print("💰 Creating Portfolio Performance Charts...")
        
        portfolio_chart = PortfolioPerformanceChart(figsize=(14, 8))
        
        # Generate portfolio performance data
        base_time = datetime.now() - timedelta(days=30)
        cumulative_pnl = 0
        
        for i in range(30):
            timestamp = base_time + timedelta(days=i)
            
            # Generate daily PnL (realistic random walk)
            daily_pnl = random.uniform(-5000, 8000)
            cumulative_pnl += daily_pnl
            
            # Generate portfolio metrics
            position_count = random.randint(5, 25)
            total_value = 100000 + random.uniform(-10000, 20000)
            
            portfolio_chart.add_performance_data(
                timestamp=timestamp,
                pnl=daily_pnl,
                cumulative_pnl=cumulative_pnl,
                position_count=position_count,
                total_value=total_value
            )
            
        try:
            # Create performance chart
            fig = portfolio_chart.plot_matplotlib("demo_portfolio_performance.png")
            print("✅ Portfolio performance chart saved to demo_portfolio_performance.png")
            
        except ImportError as e:
            print(f"❌ Portfolio performance chart failed: {e}")
            
    def demo_sentiment_analysis(self):
        """Demonstrate sentiment analysis visualization"""
        print("😊 Creating Sentiment Analysis Charts...")
        
        sentiment_chart = SentimentAnalysisPlot(figsize=(12, 8))
        
        # Generate sentiment data
        base_time = datetime.now() - timedelta(hours=72)  # 3 days
        
        for i in range(72):  # Hourly data
            timestamp = base_time + timedelta(hours=i)
            
            # Generate correlated sentiment data
            sentiment_score = random.uniform(-0.8, 0.8)
            social_volume = random.randint(100, 1000)
            news_sentiment = sentiment_score + random.uniform(-0.2, 0.2)
            fear_greed_index = 50 + (sentiment_score * 30)  # Scale to 0-100
            
            sentiment_chart.add_sentiment_data(
                timestamp=timestamp,
                sentiment_score=sentiment_score,
                social_volume=social_volume,
                news_sentiment=news_sentiment,
                fear_greed_index=fear_greed_index
            )
            
        try:
            # Create sentiment chart
            fig = sentiment_chart.plot_matplotlib("demo_sentiment_analysis.png")
            print("✅ Sentiment analysis chart saved to demo_sentiment_analysis.png")
            
        except ImportError as e:
            print(f"❌ Sentiment analysis chart failed: {e}")
            
    def demo_real_time_tracking(self):
        """Demonstrate real-time whale tracking"""
        print("⚡ Creating Real-time Whale Tracker...")
        
        tracker = RealTimeWhaleTracker(update_interval=2000)  # 2 second updates
        
        # Simulate real-time data
        symbols = ['BTC', 'ETH', 'SOL', 'ARB']
        whale_tiers = ['Whale', 'Mega Whale', 'Giant Whale']
        
        for i in range(20):  # Add 20 data points
            data_point = WhaleDataPoint(
                timestamp=datetime.now() - timedelta(seconds=20-i),
                address=f"0x{''.join(random.choices('0123456789abcdef', k=40))}",
                symbol=random.choice(symbols),
                side=random.choice(['BUY', 'SELL']),
                size=random.uniform(10, 1000),
                price=random.uniform(1000, 50000),
                volume_usd=random.uniform(50000, 5000000),
                whale_tier=random.choice(whale_tiers)
            )
            
            tracker.add_whale_data(data_point)
            
        try:
            # Create real-time animation
            anim = tracker.create_real_time_plot("demo_real_time_tracker.gif")
            print("✅ Real-time tracker animation saved to demo_real_time_tracker.gif")
            
        except ImportError as e:
            print(f"❌ Real-time tracker failed: {e}")
            
    def demo_dashboard_widgets(self):
        """Demonstrate dashboard widgets"""
        print("🎛️ Creating Dashboard Widgets...")
        
        # Create metrics widget
        metrics_widget = TradingMetricsWidget()
        
        # Add mock metrics data
        for i in range(20):
            metrics = TradingMetrics(
                timestamp=datetime.now() - timedelta(minutes=20-i),
                total_volume_24h=random.uniform(1000000, 10000000),
                whale_count_24h=random.randint(50, 200),
                buy_volume_24h=random.uniform(500000, 6000000),
                sell_volume_24h=random.uniform(500000, 6000000),
                top_whale_address="0x1234...5678",
                top_volume_24h=random.uniform(100000, 1000000),
                active_symbols=random.randint(8, 15),
                market_sentiment=random.uniform(-0.5, 0.5),
                alerts_count=random.randint(0, 10)
            )
            metrics_widget.add_metrics(metrics)
            
        # Create alert widget
        alert_widget = AlertDistributionWidget()
        
        # Add mock alert data
        from hyperliquid_monitor_plus.visualization.dashboard_components import AlertData
        
        for i in range(15):
            alert = AlertData(
                alert_id=f"alert_{i}",
                timestamp=datetime.now() - timedelta(hours=random.randint(0, 24)),
                alert_type=random.choice(['volume_spike', 'whale_detected', 'price_impact', 'sentiment_change']),
                priority=random.choice(['INFO', 'WARNING', 'CRITICAL']),
                message=f"Sample alert message {i}",
                symbol=random.choice(['BTC', 'ETH', 'SOL']),
                volume=random.uniform(100000, 5000000),
                address=f"0x{''.join(random.choices('0123456789abcdef', k=40))}"
            )
            alert_widget.add_alert(alert)
            
        # Create performance dashboard
        dashboard = PerformanceDashboard()
        dashboard.trading_metrics_widget = metrics_widget
        dashboard.alert_widget = alert_widget
        
        try:
            # Create dashboard visualization
            fig = dashboard.create_combined_dashboard()
            if fig:
                fig.write_html("demo_dashboard.html")
                print("✅ Performance dashboard saved to demo_dashboard.html")
                
        except ImportError as e:
            print(f"❌ Dashboard creation failed: {e}")
            
    def demo_report_generation(self):
        """Demonstrate report generation"""
        print("📋 Generating Comprehensive Report...")
        
        try:
            # Create HTML report
            html_generator = HTMLReportGenerator()
            
            # Add metadata
            html_generator.add_metadata("Generated by", "Hyperliquid Monitor Plus")
            html_generator.add_metadata("Report Type", "Whale Trading Analysis")
            html_generator.add_metadata("Data Period", "Last 30 Days")
            html_generator.add_metadata("Total Trades", len(self.demo_data))
            
            # Add sections
            from hyperliquid_monitor_plus.visualization.exporters import ReportSection
            
            section1 = ReportSection(
                title="Executive Summary",
                content="This report provides a comprehensive analysis of whale trading activities over the past 30 days. Key findings include increased whale activity in BTC and ETH markets, with notable price impacts following large transactions.",
                charts=["demo_whale_volume.png", "demo_market_impact.png"],
                data={
                    "Total Whale Trades": len(self.demo_data),
                    "Average Trade Size": f"${sum(dp.volume_usd for dp in self.demo_data) / len(self.demo_data):,.0f}",
                    "Most Active Symbol": "BTC",
                    "Total Volume": f"${sum(dp.volume_usd for dp in self.demo_data):,.0f}"
                }
            )
            
            section2 = ReportSection(
                title="Market Impact Analysis", 
                content="Analysis of price impacts following whale trades reveals significant market movements, particularly in smaller cap altcoins. The correlation between trade size and price impact is clearly observable.",
                charts=["demo_market_impact.png", "demo_sentiment_analysis.png"]
            )
            
            html_generator.add_section(section1)
            html_generator.add_section(section2)
            
            # Generate report
            success = html_generator.generate_report("demo_comprehensive_report.html")
            if success:
                print("✅ HTML report saved to demo_comprehensive_report.html")
                
        except ImportError as e:
            print(f"❌ Report generation failed: {e}")
            
    def check_visualization_support(self):
        """Check and display visualization library support"""
        print("🔍 Checking Visualization Support...")
        
        if not VIZ_AVAILABLE:
            print("❌ Visualization module not available")
            print(f"💡 Install with: {get_recommended_installation()}")
            return
            
        support_info = check_visualization_support()
        
        print("\n📊 Visualization Library Support:")
        for library, available in support_info.items():
            status = "✅" if available else "❌"
            print(f"   {status} {library.title()}: {'Available' if available else 'Not Available'}")
            
        if support_info['full_support']:
            print("\n🎉 All visualization features available!")
        else:
            print(f"\n💡 For full features, install: {get_recommended_installation()}")
            
    async def run_comprehensive_demo(self):
        """Run all visualization demonstrations"""
        print("🐋 Hyperliquid Monitor Plus - Visualization Demo")
        print("=" * 60)
        
        # Check support first
        self.check_visualization_support()
        
        if not VIZ_AVAILABLE:
            print("\n❌ Cannot run demo without visualization support")
            return
            
        print("\n🚀 Starting Comprehensive Visualization Demo...\n")
        
        # Run all demos
        demos = [
            ("Whale Volume Tracking", self.demo_whale_volume_chart),
            ("Market Impact Analysis", self.demo_market_impact_analysis), 
            ("Portfolio Performance", self.demo_portfolio_performance),
            ("Sentiment Analysis", self.demo_sentiment_analysis),
            ("Real-time Tracking", self.demo_real_time_tracking),
            ("Dashboard Widgets", self.demo_dashboard_widgets),
            ("Report Generation", self.demo_report_generation)
        ]
        
        for name, demo_func in demos:
            try:
                print(f"\n{'='*20} {name} {'='*20}")
                demo_func()
                await asyncio.sleep(0.1)  # Small delay between demos
            except Exception as e:
                print(f"❌ Demo '{name}' failed: {e}")
                
        # Show export statistics
        if self.exporter:
            stats = self.exporter.get_export_statistics()
            print(f"\n📊 Export Statistics:")
            print(f"   Total charts exported: {stats['total_exports']}")
            print(f"   Total size: {stats['total_size_mb']} MB")
            print(f"   Formats used: {list(stats['formats'].keys())}")
            
        print(f"\n🎉 Demo completed! Check the generated files:")
        for ext in ['*.png', '*.html', '*.gif']:
            import glob
            files = glob.glob(ext)
            for file in files:
                print(f"   📄 {file}")

async def main():
    """Main demo function"""
    demo = VisualizationDemo()
    await demo.run_comprehensive_demo()

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