"""
Core Whale Bot Module

This module contains the core whale tracking functionality with real-time detection,
intelligent analysis, and automated following capabilities.
"""

import sys
from .core import (
    WhaleBotCore,
    MonitorCore,
    WhaleDetectionEvent
)
from ..core_types import WhaleBotConfig

# Legacy function for compatibility
def create_whale_bot(config):
    """Create a whale bot instance (legacy function)"""
    return WhaleBotCore(config)


def main():
    """CLI entry point for hyperliquid-whale-bot command"""
    import argparse
    import asyncio
    import os
    from dotenv import load_dotenv
    import logging
    
    # Setup logging
    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    )
    logger = logging.getLogger(__name__)
    
    # Load environment variables
    load_dotenv()
    
    parser = argparse.ArgumentParser(
        description="Hyperliquid Whale Bot - AI-powered whale detection and following",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  hyperliquid-whale-bot --config config.json --follow-whales
  hyperliquid-whale-bot --auto-trade --min-amount 100000 --profit-target 5%
  hyperliquid-whale-bot --pattern-recognition --tier 1 --simulate
        """
    )
    
    # Config options
    parser.add_argument(
        '--config', '-c',
        help='Configuration file path (JSON or YAML)'
    )
    
    parser.add_argument(
        '--tier', '-t',
        choices=['1', '2', '3', 'all'],
        default='all',
        help='Whale tier to focus on (1=mega, 2=large, 3=medium, all=all)'
    )
    
    # Trading options
    parser.add_argument(
        '--follow-whales', '-f',
        action='store_true',
        help='Automatically follow whale trades'
    )
    
    parser.add_argument(
        '--auto-trade', '-a',
        action='store_true',
        help='Enable automatic trading (requires API keys)'
    )
    
    parser.add_argument(
        '--min-amount', '-m',
        type=float,
        default=50000,
        help='Minimum trade amount to consider (default: 50000)'
    )
    
    # Analysis options
    parser.add_argument(
        '--pattern-recognition', '-p',
        action='store_true',
        help='Enable whale pattern recognition'
    )
    
    parser.add_argument(
        '--market-impact', '-i',
        action='store_true',
        help='Enable market impact analysis'
    )
    
    parser.add_argument(
        '--cross-chain', '-x',
        action='store_true',
        help='Enable cross-chain tracking'
    )
    
    # Profit options
    parser.add_argument(
        '--profit-target', 
        type=float,
        help='Target profit percentage (e.g., 5 for 5%%)'
    )
    
    parser.add_argument(
        '--stop-loss',
        type=float,
        help='Stop loss percentage'
    )
    
    # Simulation and testing
    parser.add_argument(
        '--simulate', '-s',
        action='store_true',
        help='Run in simulation mode (no real trades)'
    )
    
    parser.add_argument(
        '--dry-run',
        action='store_true',
        help='Test mode - no actual actions'
    )
    
    # Logging options
    parser.add_argument(
        '--verbose', '-v',
        action='store_true',
        help='Verbose logging'
    )
    
    parser.add_argument(
        '--quiet', '-q',
        action='store_true',
        help='Quiet mode (minimal logging)'
    )
    
    parser.add_argument(
        '--log-file',
        help='Log file path'
    )
    
    # Integration options
    parser.add_argument(
        '--discord',
        action='store_true',
        help='Enable Discord notifications'
    )
    
    parser.add_argument(
        '--telegram',
        action='store_true',
        help='Enable Telegram notifications'
    )
    
    parser.add_argument(
        '--dashboard',
        action='store_true',
        help='Enable web dashboard'
    )
    
    parser.add_argument(
        '--dashboard-port',
        type=int,
        default=8080,
        help='Dashboard port (default: 8080)'
    )
    
    args = parser.parse_args()
    
    # Setup logging level
    if args.verbose:
        logging.getLogger().setLevel(logging.DEBUG)
    elif args.quiet:
        logging.getLogger().setLevel(logging.WARNING)
    else:
        logging.getLogger().setLevel(logging.INFO)
    
    # File logging if specified
    if args.log_file:
        handler = logging.FileHandler(args.log_file)
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        handler.setFormatter(formatter)
        logging.getLogger().addHandler(handler)
    
    try:
        # Validate API keys for trading
        if args.auto_trade and not args.simulate:
            required_keys = ['HYPERLIQUID_API_KEY', 'HYPERLIQUID_API_SECRET']
            missing_keys = [key for key in required_keys if not os.getenv(key)]
            if missing_keys:
                logger.error(f"Missing required API keys: {missing_keys}")
                logger.error("Set these in .env file or environment variables")
                sys.exit(1)
        
        # Create whale bot configuration
        config = WhaleBotConfig(
            min_whale_threshold=args.min_amount,
            enable_pattern_alerts=args.pattern_recognition,
            enable_async_processing=True,
            max_concurrent_trades=10,
            cache_market_data_seconds=5
        )
        
        # Show configuration
        if args.verbose:
            logger.info("Whale Bot Configuration:")
            for key, value in config.__dict__.items():
                logger.info(f"  {key}: {value}")
        
        if args.dry_run:
            logger.info("DRY RUN: Would start whale bot with:")
            logger.info(f"  Tier: {args.tier}")
            logger.info(f"  Follow whales: {args.follow_whales}")
            logger.info(f"  Auto trade: {args.auto_trade}")
            logger.info(f"  Min amount: {args.min_amount}")
            logger.info(f"  Simulate: {args.simulate}")
            return
        
        logger.info("Starting Hyperliquid Whale Bot...")
        logger.info(f"Mode: {'Simulation' if args.simulate else 'Live'}")
        logger.info(f"Tier: {args.tier}")
        
        # Create and start whale bot
        async def run_bot():
            bot = WhaleBotCore(config)
            
            try:
                await bot.start()
                logger.info("Whale bot started successfully")
                logger.info("Press Ctrl+C to stop")
                
                # Keep running
                while True:
                    await asyncio.sleep(1)
                    
            except KeyboardInterrupt:
                logger.info("Bot stopped by user")
            except Exception as e:
                logger.error(f"Bot error: {e}")
                raise
            finally:
                await bot.stop()
        
        # Start the bot
        if config.dashboard:
            logger.info(f"Starting web dashboard on port {config.dashboard_port}")
            # Dashboard would be started here
            logger.info("Dashboard integration not yet implemented")
        
        asyncio.run(run_bot())
        
    except Exception as e:
        logger.error(f"Whale bot error: {e}")
        if args.verbose:
            import traceback
            traceback.print_exc()
        sys.exit(1)


if __name__ == "__main__":
    main()

__all__ = [
    "WhaleBotCore",
    "MonitorCore", 
    "WhaleDetectionEvent",
    "create_whale_bot"
]
