#!/usr/bin/env python3
"""
Monitoring Module Example - Real-time Hyperliquid Data Monitoring

This example demonstrates how to use the monitoring system to track
real-time trades, user activity, and market data from Hyperliquid DEX.
"""

import asyncio
import json
from datetime import datetime, timedelta
from typing import Dict, List, Optional

# Import monitoring components
from hyperliquid_monitor_plus.monitor import HyperliquidMonitor
from hyperliquid_monitor_plus.monitor_types import Trade, TradeSide, TradeType
from hyperliquid_monitor_plus.database import TradeDatabase
from hyperliquid_monitor_plus.config import get_demo_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 WhaleMonitorDemo:
    """Demonstration of whale monitoring capabilities"""
    
    def __init__(self):
        self.db = TradeDatabase("demo_whale_trades.db")
        self.config = get_demo_config()
        self.monitor = None
        self.whale_addresses = [
            "0x010461C14e146ac35Fe42271BDC1134EE31C703a",
            "0x8eb8a3b98659Cce290402893d0123abb75E3ab28",
            "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
            "0x00000000219ab540356cbb839cbe05303d7705fa"
        ]
        
    def validate_ethereum_address(self, address: str) -> bool:
        """Validate Ethereum address format"""
        if not address:
            return False
        
        # Remove 0x prefix if present
        clean_address = address.replace('0x', '')
        
        # Check length and hex format
        return len(clean_address) == 40 and all(c in '0123456789abcdefABCDEF' for c in clean_address)
    
    def trade_callback(self, trade: Trade) -> None:
        """Callback function for new trades"""
        if trade.user in self.whale_addresses:
            formatted_side = "BUY" if trade.side == TradeSide.BUY else "SELL"
            
            logger.info(f"🐋 WHALE TRADE DETECTED!")
            logger.info(f"   Address: {trade.user[:16]}...")
            logger.info(f"   Coin: {trade.coin}")
            logger.info(f"   Side: {formatted_side}")
            logger.info(f"   Size: {trade.size:.4f}")
            logger.info(f"   Price: ${trade.price:,.2f}")
            logger.info(f"   Value: ${trade.size * trade.price:,.2f}")
            
            # Store in database
            try:
                self.db.insert_trade(trade)
                logger.info("💾 Trade stored in database")
            except Exception as e:
                logger.error(f"Failed to store trade: {e}")
    
    def market_callback(self, market_data: dict) -> None:
        """Callback for market data updates"""
        if 'allMids' in market_data:
            logger.info(f"📊 Market Update: {len(market_data['allMids'])} prices updated")
    
    async def start_basic_monitoring(self):
        """Start basic trade monitoring"""
        print("🔍 Basic Trade Monitoring Demo")
        print("=" * 50)
        
        # Initialize monitor (demo mode)
        print("🚀 Initializing monitor...")
        
        # Note: In production, you would use real API
        print(f"📡 Monitor initialized (demo mode)")
        print(f"👁️  Monitoring {len(self.whale_addresses)} whale addresses")
        
        # Simulate some trades for demo
        await self.simulate_whale_trades()
        
        print("✅ Basic monitoring demo completed!")
    
    async def start_advanced_monitoring(self):
        """Start advanced monitoring with multiple data feeds"""
        print("\n🎯 Advanced Monitoring Demo")
        print("=" * 50)
        
        print("📈 Setting up multiple data feeds:")
        print("   - Trade fills")
        print("   - Order book updates") 
        print("   - User events")
        print("   - Funding updates")
        print("   - Candlestick data")
        
        # Simulate advanced monitoring
        await self.simulate_advanced_feeds()
        
        print("✅ Advanced monitoring demo completed!")
    
    async def start_user_monitoring(self):
        """Monitor specific user activity"""
        print("\n👤 User Activity Monitoring")
        print("=" * 50)
        
        target_user = self.whale_addresses[0]
        print(f"👁️  Focusing on user: {target_user[:16]}...")
        
        # Simulate user-specific monitoring
        await self.simulate_user_activity(target_user)
        
        print("✅ User monitoring demo completed!")
    
    async def start_market_analysis(self):
        """Real-time market analysis"""
        print("\n📊 Real-time Market Analysis")
        print("=" * 50)
        
        tracked_coins = ["ETH", "BTC", "SOL", "AVAX", "LINK"]
        print(f"📈 Analyzing markets: {', '.join(tracked_coins)}")
        
        await self.simulate_market_analysis(tracked_coins)
        
        print("✅ Market analysis demo completed!")
    
    async def simulate_whale_trades(self):
        """Simulate whale trades for demo"""
        
        sample_trades = [
            {
                "user": self.whale_addresses[0],
                "coin": "ETH",
                "side": TradeSide.BUY,
                "size": 150.5,
                "price": 2450.75,
                "timestamp": datetime.now()
            },
            {
                "user": self.whale_addresses[1],
                "coin": "BTC", 
                "side": TradeSide.SELL,
                "size": 30.2,
                "price": 45200.00,
                "timestamp": datetime.now()
            },
            {
                "user": self.whale_addresses[2],
                "coin": "SOL",
                "side": TradeSide.BUY,
                "size": 2500.0,
                "price": 95.50,
                "timestamp": datetime.now()
            }
        ]
        
        print(f"\n📡 Simulating {len(sample_trades)} whale trades:")
        
        for trade_data in sample_trades:
            trade = Trade(**trade_data)
            print(f"\n🔔 New trade: {trade.user[:16]}... {trade.side.value} {trade.size} {trade.coin}")
            self.trade_callback(trade)
            await asyncio.sleep(1)
    
    async def simulate_advanced_feeds(self):
        """Simulate various data feeds"""
        
        feeds = [
            {"type": "l2Book", "coin": "ETH", "data": {"bids": [[2450.75, 10.5]], "asks": [[2451.25, 15.2]]}},
            {"type": "userEvents", "user": self.whale_addresses[0], "data": {"positions": [{"coin": "ETH", "size": 150.5}]}},
            {"type": "candle", "coin": "BTC", "data": {"open": 45200, "high": 45300, "low": 45100, "close": 45250}},
            {"type": "userFills", "user": self.whale_addresses[1], "data": [{"coin": "BTC", "side": "B", "size": 30.2, "price": 45200}]}
        ]
        
        print(f"\n📡 Simulating {len(feeds)} data feeds:")
        
        for feed in feeds:
            print(f"   📡 {feed['type']} feed update")
            if 'data' in feed:
                print(f"      {str(feed['data'])[:100]}...")
            await asyncio.sleep(0.5)
    
    async def simulate_user_activity(self, user: str):
        """Simulate user-specific activity"""
        
        activities = [
            {"type": "position_update", "coin": "ETH", "size": 150.5, "pnl": 2500.75},
            {"type": "order_placed", "coin": "BTC", "side": "BUY", "size": 25.0, "price": 45000},
            {"type": "funding_payment", "amount": -125.50, "coin": "ETH"},
            {"type": "withdrawal", "coin": "USDC", "amount": 50000}
        ]
        
        print(f"\n👤 User activity for {user[:16]}...")
        
        for activity in activities:
            print(f"   📋 {activity['type']}: {activity}")
            await asyncio.sleep(0.5)
    
    async def simulate_market_analysis(self, coins: List[str]):
        """Simulate market analysis data"""
        
        analysis_data = {}
        
        for coin in coins:
            analysis_data[coin] = {
                "price": 1000 + hash(coin) % 50000,
                "volume_24h": 1000000 + hash(coin) % 10000000,
                "volatility": 0.15 + (hash(coin) % 100) / 1000,
                "whale_activity": "HIGH" if hash(coin) % 3 == 0 else "MEDIUM"
            }
        
        print(f"\n📊 Market analysis for {len(coins)} coins:")
        
        for coin, data in analysis_data.items():
            print(f"   📈 {coin:6}: ${data['price']:>8,.2f} | "
                  f"Vol: ${data['volume_24h']:>12,.0f} | "
                  f"Activity: {data['whale_activity']}")
            await asyncio.sleep(0.3)
    
    async def database_demo(self):
        """Demonstrate database operations"""
        print("\n💾 Database Operations Demo")
        print("=" * 50)
        
        # Insert sample data
        sample_trade = Trade(
            user=self.whale_addresses[0],
            coin="ETH",
            side=TradeSide.BUY,
            size=100.0,
            price=2400.00,
            timestamp=datetime.now()
        )
        
        self.db.insert_trade(sample_trade)
        print("✅ Sample trade inserted")
        
        # Query statistics
        stats = self.db.get_address_statistics(self.whale_addresses[0])
        print(f"📊 Address statistics:")
        print(f"   Total fills: {stats['total_fills']}")
        print(f"   Buy trades: {stats['buy_count']}")
        print(f"   Total volume: ${stats['total_volume']:,.2f}")
        
        # Get recent activity
        recent = self.db.get_recent_activity(minutes=60)
        print(f"📝 Recent activity: {len(recent)} trades")
        
        print("✅ Database demo completed!")
    
    async def run_all_demos(self):
        """Run all monitoring demonstrations"""
        print("🎯 HYPERLIQUID MONITOR PLUS - MONITORING MODULE EXAMPLES")
        print("=" * 70)
        
        # Validate addresses
        print("🔍 Validating whale addresses:")
        valid_addresses = []
        for address in self.whale_addresses:
            if self.validate_ethereum_address(address):
                print(f"   ✅ {address[:16]}... (valid)")
                valid_addresses.append(address)
            else:
                print(f"   ❌ {address[:16]}... (invalid)")
        
        if not valid_addresses:
            print("⚠️  No valid addresses found!")
            return
        
        print(f"\n📍 Using {len(valid_addresses)} valid addresses")
        
        # Run individual demos
        await self.start_basic_monitoring()
        await self.start_advanced_monitoring()
        await self.start_user_monitoring()
        await self.start_market_analysis()
        await self.database_demo()
        
        # Summary
        print("\n" + "=" * 70)
        print("🎉 All monitoring demos completed successfully!")
        print("💡 Key features demonstrated:")
        print("   📡 Real-time trade monitoring")
        print("   🐋 Whale detection and alerts") 
        print("   💾 Database storage and analysis")
        print("   📊 Market data feeds")
        print("   👤 User activity tracking")
        print("   📈 Multi-coin market analysis")
        
        # Clean up
        self.db.close()
        print("\n🧹 Database connection closed")


async def configuration_demo():
    """Demonstrate configuration options"""
    print("\n⚙️  Configuration Options")
    print("=" * 50)
    
    demo_config = get_demo_config()
    print(f"🔧 Demo Configuration:")
    print(f"   Max Whales: {demo_config.max_whales}")
    print(f"   Alert Threshold: ${demo_config.alert_threshold:,.2f}")
    print(f"   Conservative Mode: {demo_config.conservative_mode}")
    
    # Show environment variable usage
    print(f"\n🌍 Environment Variables:")
    print(f"   HYPERLIQUID_API_URL")
    print(f"   HYPERLIQUID_WS_URL") 
    print(f"   WHALE_MONITOR_ADDRESSES")
    print(f"   DATABASE_PATH")


async def main():
    """Main demonstration function"""
    
    # Show configuration
    await configuration_demo()
    
    # Run monitoring demos
    monitor_demo = WhaleMonitorDemo()
    await monitor_demo.run_all_demos()


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