#!/usr/bin/env python3
"""
Main Examples Runner - Run all Hyperliquid Monitor Plus examples

This script runs comprehensive demonstrations of all library modules.
Use this to quickly test all features or showcase the library capabilities.
"""

import asyncio
import sys
import os
from pathlib import Path

# Add library to path
sys.path.insert(0, str(Path(__file__).parent.parent))

def print_banner():
    """Print welcome banner"""
    print("🐋" * 20)
    print("🎯 HYPERLIQUID MONITOR PLUS - COMPLETE EXAMPLES")
    print("🐋" * 20)
    print()
    print("This demonstration showcases all modules and capabilities:")
    print("🔧 Core whale bot functionality")
    print("📡 Real-time monitoring system") 
    print("📊 Market analysis and impact")
    print("🧠 AI-powered intelligence")
    print("🎯 Advanced tracking system")
    print("⚙️  Configuration management")
    print("💾 Database operations")
    print("🔗 Integration capabilities")
    print("🚨 Multi-channel notifications")
    print("🎲 Strategy analysis")
    print()

def show_menu():
    """Show example selection menu"""
    examples = [
        ("1", "Core Module", "Run whale bot core examples"),
        ("2", "Monitoring", "Run real-time monitoring examples"),
        ("3", "Analysis", "Run market analysis examples"),
        ("4", "Intelligence", "Run AI intelligence examples"),
        ("5", "Tracking", "Run advanced tracking examples"),
        ("6", "Configuration", "Run configuration examples"),
        ("7", "Database", "Run database operation examples"),
        ("8", "Integration", "Run integration examples"),
        ("9", "Notifications", "Run alert system examples"),
        ("10", "Strategy", "Run strategy analysis examples"),
        ("A", "All Examples", "Run all examples in sequence"),
        ("Q", "Quit", "Exit the program")
    ]
    
    print("📋 SELECT AN EXAMPLE TO RUN:")
    print()
    for key, title, description in examples:
        print(f"   {key:2} - {title:<15} {description}")
    print()

async def run_example(category):
    """Run a specific example category"""
    try:
        if category == "1":  # Core
            from examples.core.whale_bot_example import main
            await main()
        elif category == "2":  # Monitoring
            from examples.monitoring.basic_monitoring import main
            await main()
        elif category == "3":  # Analysis
            from examples.analysis.market_analysis import main
            await main()
        elif category == "4":  # Intelligence
            from examples.intelligence.intelligence_demo import main
            await main()
        elif category == "5":  # Tracking
            from examples.tracking.advanced_tracking import main
            await main()
        elif category == "6":  # Configuration
            from examples.configuration.advanced_config import main
            main()
        elif category == "7":  # Database
            from examples.database.data_analysis import main
            await main()
        elif category == "8":  # Integration
            from examples.integration.dashboard_integration import main
            await main()
        elif category == "9":  # Notifications
            from examples.notifications.alert_system import main
            await main()
        elif category == "10":  # Strategy
            from examples.strategy.strategy_analyzer import main
            await main()
        else:
            print(f"❌ Unknown category: {category}")
            return False
            
        return True
        
    except Exception as e:
        print(f"❌ Error running example {category}: {e}")
        return False

async def run_all_examples():
    """Run all examples in sequence"""
    print("🚀 RUNNING ALL EXAMPLES")
    print("=" * 50)
    
    categories = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
    successful = 0
    
    for i, category in enumerate(categories, 1):
        print(f"\n📍 Example {i}/10: Running category {category}")
        print("-" * 30)
        
        success = await run_example(category)
        if success:
            successful += 1
        
        # Brief pause between examples
        if i < len(categories):
            print(f"\n⏸️  Pausing before next example...")
            await asyncio.sleep(2)
    
    print(f"\n🏁 ALL EXAMPLES COMPLETED")
    print(f"✅ Successful: {successful}/{len(categories)}")
    print(f"📊 Success Rate: {(successful/len(categories))*100:.1f}%")

async def interactive_mode():
    """Interactive mode for running specific examples"""
    while True:
        show_menu()
        
        choice = input("👉 Enter your choice: ").strip().upper()
        
        if choice == "Q":
            print("👋 Goodbye!")
            break
        elif choice == "A":
            await run_all_examples()
        elif choice in ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]:
            print(f"\n🎯 Running example {choice}...")
            await run_example(choice)
        else:
            print("❌ Invalid choice. Please try again.")
        
        # Ask to continue
        continue_choice = input("\n🔄 Continue? (Y/n): ").strip().lower()
        if continue_choice in ['n', 'no', 'q', 'quit']:
            print("👋 Goodbye!")
            break
        
        print("\n" + "="*50 + "\n")

def show_example_info():
    """Show information about available examples"""
    print("📚 EXAMPLE INFORMATION")
    print("=" * 50)
    
    categories = {
        "Core": "Basic whale bot setup, configuration, and real-time detection",
        "Monitoring": "Hyperliquid API integration, trade tracking, and market data",
        "Analysis": "Market impact analysis, whale classification, and correlation",
        "Intelligence": "AI-powered sentiment analysis, pattern recognition, and predictions",
        "Tracking": "Cross-chain tracking, ML predictions, and advanced alerts",
        "Configuration": "Basic/custom configs, Phase 3 features, and optimization",
        "Database": "Trade storage, analytics, portfolio tracking, and maintenance",
        "Integration": "Dashboard updates, webhooks, APIs, and external services",
        "Notifications": "Telegram/Discord alerts, custom rules, and alert management",
        "Strategy": "Behavior analysis, performance metrics, and optimization"
    }
    
    for category, description in categories.items():
        print(f"📁 {category}")
        print(f"   {description}")
        print()

def main():
    """Main entry point"""
    print_banner()
    
    # Check for command line arguments
    if len(sys.argv) > 1:
        choice = sys.argv[1].upper()
        
        if choice == "--help" or choice == "-h":
            print("Usage: python run_examples.py [OPTION]")
            print()
            print("Options:")
            print("  --all, -a      Run all examples")
            print("  --info, -i     Show example information")
            print("  --help, -h     Show this help message")
            print("  (1-10)         Run specific example category")
            print()
            print("Without arguments, starts interactive mode.")
            return
        
        if choice == "--info" or choice == "-i":
            show_example_info()
            return
        
        if choice == "--all" or choice == "-a":
            asyncio.run(run_all_examples())
            return
        
        # Run specific example
        if choice in ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]:
            asyncio.run(run_example(choice))
            return
        
        print(f"❌ Unknown option: {choice}")
        print("Use --help for usage information.")
        return
    
    # Interactive mode
    try:
        asyncio.run(interactive_mode())
    except KeyboardInterrupt:
        print("\n\n👋 Interrupted by user. Goodbye!")
    except Exception as e:
        print(f"\n❌ Unexpected error: {e}")

if __name__ == "__main__":
    main()