#!/usr/bin/env python3
"""
Database Module Example - Data Storage and Analysis

This example demonstrates database operations including:
- Trade data storage and retrieval
- Performance analytics
- Historical analysis
- Whale behavior tracking
"""

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

# Import database components
from hyperliquid_monitor_plus.database import TradeDatabase
from hyperliquid_monitor_plus.monitor_types import Trade, TradeSide, TradeType

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


class DatabaseDemo:
    """Demonstration of database operations"""
    
    def __init__(self):
        self.db = TradeDatabase("demo_whale_database.db")
    
    async def basic_operations_demo(self):
        """Demonstrate basic database operations"""
        print("💾 Basic Database Operations")
        print("=" * 50)
        
        # Sample whale trades
        sample_trades = [
            Trade(
                user="0x010461C14e146ac35Fe42271BDC1134EE31C703a",
                coin="ETH",
                side=TradeSide.BUY,
                size=150.5,
                price=2450.75,
                timestamp=datetime.now() - timedelta(hours=2)
            ),
            Trade(
                user="0x8eb8a3b98659Cce290402893d0123abb75E3ab28",
                coin="BTC",
                side=TradeSide.SELL,
                size=25.2,
                price=45200.00,
                timestamp=datetime.now() - timedelta(hours=1)
            ),
            Trade(
                user="0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
                coin="SOL",
                side=TradeSide.BUY,
                size=2500.0,
                price=95.50,
                timestamp=datetime.now() - timedelta(minutes=30)
            )
        ]
        
        print("📊 Inserting sample trades:")
        for i, trade in enumerate(sample_trades, 1):
            print(f"   {i}. {trade.user[:16]}... | {trade.side.value} {trade.size} {trade.coin} @ ${trade.price:,.2f}")
            self.db.insert_trade(trade)
        
        print("✅ Basic operations demo completed!")
    
    async def statistics_demo(self):
        """Demonstrate statistics retrieval"""
        print("\n📊 Statistics and Analytics Demo")
        print("=" * 50)
        
        whale_address = "0x010461C14e146ac35Fe42271BDC1134EE31C703a"
        
        # Get address statistics
        stats = self.db.get_address_statistics(whale_address)
        
        print(f"📈 ADDRESS STATISTICS for {whale_address[:16]}...")
        print(f"   Total Fills: {stats['total_fills']}")
        print(f"   Buy Count: {stats['buy_count']}")
        print(f"   Sell Count: {stats['sell_count']}")
        print(f"   Total Volume: ${stats['total_volume']:,.2f}")
        print(f"   Buy Volume: ${stats['buy_volume']:,.2f}")
        print(f"   Sell Volume: ${stats['sell_volume']:,.2f}")
        print(f"   Total PnL: ${stats['total_pnl']:,.2f}")
        print(f"   Total Fees: ${stats['total_fees']:.4f}")
        
        if stats['top_coins']:
            print(f"\n🏆 TOP TRADED COINS:")
            for coin, count in stats['top_coins'][:5]:
                print(f"   {coin:8} - {count} trades")
        
        print(f"\n📅 ACTIVITY PERIOD:")
        print(f"   First Trade: {stats['first_trade']}")
        print(f"   Last Trade: {stats['last_trade']}")
        
        print("✅ Statistics demo completed!")
    
    async def recent_activity_demo(self):
        """Demonstrate recent activity tracking"""
        print("\n⏰ Recent Activity Tracking")
        print("=" * 50)
        
        # Get recent activity
        recent_trades = self.db.get_recent_activity(minutes=60)
        
        if recent_trades:
            print(f"📝 Recent Activity (Last 60 minutes): {len(recent_trades)} trades")
            print(f"{'Time':<12} {'Address':<18} {'Coin':<6} {'Side':<4} {'Size':<10} {'Price':<12}")
            print("-" * 70)
            
            for trade in recent_trades[:10]:  # Show first 10
                timestamp = trade[1]
                address = trade[2][:16] + "..."
                coin = trade[3]
                side = trade[4]
                size = trade[5]
                price = trade[6]
                
                print(f"{timestamp:<12} {address:<18} {coin:<6} {side:<4} {size:<10.2f} ${price:<11,.2f}")
        else:
            print("📝 No recent activity found")
        
        print("✅ Recent activity demo completed!")
    
    async def fills_analysis_demo(self):
        """Demonstrate fills analysis"""
        print("\n📋 Fills Analysis Demo")
        print("=" * 50)
        
        # Get fills for specific address
        whale_address = "0x8eb8a3b98659Cce290402893d0123abb75E3ab28"
        fills = self.db.get_fills_by_address(whale_address, limit=10)
        
        if fills:
            print(f"📋 RECENT FILLS for {whale_address[:16]}...")
            print(f"{'Time':<12} {'Coin':<6} {'Side':<4} {'Size':<10} {'Price':<12} {'Value':<15}")
            print("-" * 65)
            
            total_value = 0
            for fill in fills:
                timestamp = fill[1]
                coin = fill[3]
                side = fill[4]
                size = fill[5]
                price = fill[6]
                value = size * price
                total_value += value
                
                side_arrow = "📈" if side == "BUY" else "📉"
                print(f"{timestamp:<12} {coin:<6} {side_arrow}{side:<3} {size:<10.4f} ${price:<11,.2f} ${value:<14,.2f}")
            
            print("-" * 65)
            print(f"{'TOTAL VALUE':<46} ${total_value:,.2f}")
        else:
            print("📋 No fills found for this address")
        
        print("✅ Fills analysis demo completed!")
    
    async def coin_analysis_demo(self):
        """Demonstrate coin-specific analysis"""
        print("\n🪙 Coin-Specific Analysis Demo")
        print("=" * 50)
        
        whale_address = "0x010461C14e146ac35Fe42271BDC1134EE31C703a"
        coins = ["ETH", "BTC", "SOL"]
        
        print(f"🪙 COIN ANALYSIS for {whale_address[:16]}...")
        
        for coin in coins:
            summary = self.db.get_coin_summary(whale_address, coin)
            
            if summary['total_trades'] > 0:
                print(f"\n   📊 {coin} Analysis:")
                print(f"      Total Trades: {summary['total_trades']}")
                print(f"      Buy Count: {summary['buy_count']}")
                print(f"      Sell Count: {summary['sell_count']}")
                print(f"      Total Bought: {summary['total_bought']:.4f}")
                print(f"      Total Sold: {summary['total_sold']:.4f}")
                print(f"      Net Position: {summary['net_position']:.4f}")
                print(f"      Avg Buy Price: ${summary['avg_buy_price']:,.2f}")
                print(f"      Avg Sell Price: ${summary['avg_sell_price']:,.2f}")
                print(f"      Total PnL: ${summary['total_pnl']:,.2f}")
                
                # Performance metrics
                if summary['buy_count'] > 0 and summary['sell_count'] > 0:
                    price_spread = summary['avg_sell_price'] - summary['avg_buy_price']
                    spread_percent = (price_spread / summary['avg_buy_price']) * 100
                    print(f"      Price Spread: ${price_spread:,.2f} ({spread_percent:+.2f}%)")
            else:
                print(f"   📊 {coin}: No trading activity")
        
        print("✅ Coin analysis demo completed!")
    
    async def portfolio_analysis_demo(self):
        """Demonstrate portfolio analysis"""
        print("\n💼 Portfolio Analysis Demo")
        print("=" * 50)
        
        whale_address = "0x010461C14e146ac35Fe42271BDC1134EE31C703a"
        
        # Get current portfolio
        portfolio = self.db.get_portfolio_snapshot(whale_address)
        
        print(f"💼 PORTFOLIO SNAPSHOT for {whale_address[:16]}...")
        
        if portfolio:
            total_value = 0
            total_pnl = 0
            
            print(f"{'Coin':<6} {'Position':<12} {'Entry Price':<12} {'Current Price':<13} {'PnL':<12} {'PnL %':<8}")
            print("-" * 70)
            
            for position in portfolio:
                coin = position['coin']
                size = position['size']
                avg_price = position['avg_entry_price']
                current_price = position['current_price']
                pnl = position['unrealized_pnl']
                pnl_percent = position['pnl_percentage']
                position_value = size * current_price
                
                total_value += position_value
                total_pnl += pnl
                
                pnl_emoji = "🟢" if pnl > 0 else "🔴" if pnl < 0 else "⚪"
                
                print(f"{coin:<6} {size:<12.4f} ${avg_price:<11,.2f} ${current_price:<12,.2f} "
                      f"${pnl:<11,.2f} {pnl_emoji}{pnl_percent:+.2f}%")
            
            print("-" * 70)
            print(f"{'TOTAL':<31} ${total_value:,.2f} ${total_pnl:,.2f} "
                  f"{'🟢' if total_pnl > 0 else '🔴'}{total_pnl/(total_value-total_pnl)*100 if total_value-total_pnl != 0 else 0:+.2f}%")
        else:
            print("💼 No portfolio positions found")
        
        print("✅ Portfolio analysis demo completed!")
    
    async def performance_tracking_demo(self):
        """Demonstrate performance tracking"""
        print("\n📈 Performance Tracking Demo")
        print("=" * 50)
        
        whale_address = "0x8eb8a3b98659cce290402893d0123abb75E3ab28"
        
        # Get performance metrics
        performance = self.db.get_performance_metrics(whale_address, days=30)
        
        print(f"📈 30-DAY PERFORMANCE for {whale_address[:16]}...")
        
        if performance:
            print(f"💰 Total Return: ${performance['total_return']:,.2f}")
            print(f"📊 Return %: {performance['return_percentage']:+.2f}%")
            print(f"🎯 Win Rate: {performance['win_rate']:.2f}")
            print(f"⚡ Average Trade Size: ${performance['avg_trade_size']:,.2f}")
            print(f"📈 Best Trade: ${performance['best_trade']:,.2f}")
            print(f"📉 Worst Trade: ${performance['worst_trade']:,.2f}")
            print(f"🔄 Total Trades: {performance['total_trades']}")
            print(f"⏱️  Avg Hold Time: {performance['avg_hold_time_hours']:.1f} hours")
            
            # Risk metrics
            print(f"\n⚠️  RISK METRICS:")
            print(f"   Max Drawdown: ${performance['max_drawdown']:,.2f}")
            print(f"   Sharpe Ratio: {performance['sharpe_ratio']:.2f}")
            print(f"   Volatility: {performance['volatility']:.2f}")
            
            # Monthly breakdown
            print(f"\n📅 MONTHLY BREAKDOWN:")
            for month_data in performance['monthly_returns']:
                month = month_data['month']
                return_pct = month_data['return_percentage']
                emoji = "🟢" if return_pct > 0 else "🔴"
                print(f"   {month}: {emoji}{return_pct:+.2f}%")
        else:
            print("📈 Insufficient data for performance analysis")
        
        print("✅ Performance tracking demo completed!")
    
    async def data_export_demo(self):
        """Demonstrate data export functionality"""
        print("\n📤 Data Export Demo")
        print("=" * 50)
        
        whale_address = "0x010461C14e146ac35Fe42271BDC1134EE31C703a"
        
        # Export trade history
        trade_history = self.db.export_trade_history(whale_address, days=7)
        
        print(f"📤 EXPORTING TRADE HISTORY for {whale_address[:16]}...")
        print(f"   Time Period: Last 7 days")
        print(f"   Total Records: {len(trade_history)}")
        
        if trade_history:
            # Show sample data
            print(f"\n   Sample Records:")
            print(f"   {trade_history[0]}")
            
            # Export to JSON (simulated)
            export_data = {
                "address": whale_address,
                "export_date": datetime.now().isoformat(),
                "time_period": "7_days",
                "total_records": len(trade_history),
                "trades": trade_history
            }
            
            print(f"   ✅ Data prepared for export to JSON")
            print(f"   📊 Export Size: {len(json.dumps(export_data))} bytes")
        else:
            print("   ⚠️  No data found for export")
        
        print("✅ Data export demo completed!")
    
    async def database_maintenance_demo(self):
        """Demonstrate database maintenance"""
        print("\n🧹 Database Maintenance Demo")
        print("=" * 50)
        
        # Database optimization
        print("🧹 OPTIMIZING DATABASE...")
        self.db.optimize_database()
        print("   ✅ Database optimized")
        
        # Cleanup old data (simulated)
        print("\n🗑️  CLEANING OLD DATA...")
        deleted_rows = self.db.cleanup_old_data(days=90)
        print(f"   🗑️  Deleted {deleted_rows} old records")
        
        # Backup database (simulated)
        print("\n💾 CREATING BACKUP...")
        backup_path = self.db.create_backup(f"backup_{datetime.now().strftime('%Y%m%d_%H%M%S')}.db")
        print(f"   💾 Backup created: {backup_path}")
        
        # Get database statistics
        print("\n📊 DATABASE STATISTICS:")
        stats = self.db.get_database_stats()
        print(f"   📋 Total Records: {stats['total_records']}")
        print(f"   📁 Database Size: {stats['database_size_mb']:.2f} MB")
        print(f"   🗃️  Tables: {stats['table_count']}")
        print(f"   📅 Oldest Record: {stats['oldest_record']}")
        print(f"   📅 Newest Record: {stats['newest_record']}")
        
        print("✅ Database maintenance demo completed!")
    
    async def run_all_demos(self):
        """Run all database demonstrations"""
        print("🎯 HYPERLIQUID MONITOR PLUS - DATABASE MODULE EXAMPLES")
        print("=" * 70)
        
        # Add sample data first
        await self.basic_operations_demo()
        
        # Run analytics demos
        await self.statistics_demo()
        await self.recent_activity_demo()
        await self.fills_analysis_demo()
        await self.coin_analysis_demo()
        await self.portfolio_analysis_demo()
        await self.performance_tracking_demo()
        await self.data_export_demo()
        await self.database_maintenance_demo()
        
        print("\n" + "=" * 70)
        print("🎉 All database demos completed successfully!")
        print("💡 Database capabilities demonstrated:")
        print("   💾 Trade data storage and retrieval")
        print("   📊 Performance analytics")
        print("   💼 Portfolio tracking")
        print("   📈 Historical analysis")
        print("   📤 Data export functionality")
        print("   🧹 Database maintenance")
        
        # Clean up
        self.db.close()
        print("\n🧹 Database connection closed")


async def main():
    """Main demonstration function"""
    
    # Run database demos
    db_demo = DatabaseDemo()
    await db_demo.run_all_demos()


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