"""
Hyperliquid Monitor Plus Enhanced - Production-Ready Version

A comprehensive and advanced monitor for tracking whale wallet transactions on Hyperliquid DEX.

Features:
- Correct side mapping (A=SELL, B=BUY) 
- Proper address handling
- Support for multiple addresses simultaneously
- Thread-safe database operations
- Production-ready error handling and logging
- Smart alert system with configurable conditions
- PnL (Profit/Loss) analyzer with position tracking
- Advanced whale tracking with intelligence

Author: Pezhman Hajipour
Version: 3.0.0
License: MIT
"""

__version__ = "3.0.0"
__author__ = "Pezhman Hajipour"
__license__ = "MIT"

# Core imports - these are the essential components
from hyperliquid_monitor_plus.monitor import HyperliquidMonitor, validate_address
from hyperliquid_monitor_plus.database import TradeDatabase, init_database, Database
from hyperliquid_monitor_plus.core_types import Trade, TradeCallback, TradeType, TradeSide
from hyperliquid_monitor_plus.utils.type_adapters import (
    side_to_trade_side,
    trade_side_to_side,
    is_buy_side,
    is_sell_side,
)

# SDK adapter functions
from hyperliquid_monitor_plus.utils.sdk_adapter import get_info, get_api_url

# Whale Bot Core (legacy compatibility)
from hyperliquid_monitor_plus.core import WhaleBotCore, MonitorCore, WhaleDetectionEvent

# Visualization module (requires viz extras)
try:
    from hyperliquid_monitor_plus.visualization import (
        # Plot classes
        WhaleVolumeChart,
        MarketImpactPlot,
        TradeDistributionChart,
        PortfolioPerformanceChart,
        SentimentAnalysisPlot,
        CorrelationHeatmap,
        RealTimeWhaleTracker,
        
        # Dashboard components
        TradingMetricsWidget,
        AlertDistributionWidget,
        PerformanceDashboard,
        RealTimeChart,
        
        # Exporters
        ChartExporter,
        HTMLReportGenerator,
        PDFReportGenerator,
        
        # Utility functions
        check_visualization_support,
        get_recommended_installation
    )
    _VIZ_AVAILABLE = True
except ImportError:
    _VIZ_AVAILABLE = False

# Enhanced types
from hyperliquid_monitor_plus.core_types.types import (
    EnhancedTrade,
    WhaleTier,
    TradeUrgency,
    FollowRecommendation,
    WhalePattern,
    MarketImpactAnalysis,
    PredictionResult,
    RiskAssessment,
    BaseType
)

# Legacy function - maintained for compatibility
create_whale_bot = WhaleBotCore

# Config is optional - users can import if needed
try:
    from hyperliquid_monitor_plus import config
except ImportError:
    config = None

__all__ = [
    "HyperliquidMonitor",
    "TradeDatabase",
    "Database",  # Alias for TradeDatabase
    "Trade",
    "TradeCallback",
    "TradeType",
    "TradeSide",
    "validate_address",
    "init_database",
    "get_info",
    "get_api_url",
    "config",
    # Utility functions
    "side_to_trade_side",
    "trade_side_to_side",
    "is_buy_side",
    "is_sell_side",
    # Alert system
    "AlertManager",
    "AlertCondition",
    "Alert",
    "AlertLevel",
    "AlertType",
    "AlertCallback",
    "TradeFilter",
    "AlertFilter",
    # PnL system
    "PnLManager",
    "PnLCalculator",
    "Position",
    "PnLRecord",
    "CoinPnL",
    "PortfolioPnL",
    "PositionSide",
    "PnLCallback",
    # Position Tracker system
    "PositionTracker",
    "LivePosition",
    "PositionChange",
    "PositionSnapshot",
    "AccountState",
    "PositionEventType",
    "PositionChangeCallback",
    "SnapshotCallback",
    # Strategy Analyzer system
    "StrategyAnalyzer",
    "StrategyMetrics",
    "TradePattern",
    "StrategyComparison",
    "TimeAnalysis",
    "StrategyRecommendation",
    "PatternType",
    "RecommendationType",
    "AnalysisCallback",
    # Reporting system
    "ReportGenerator",
    "ReportConfig",
    "ReportFormat",
    "ReportType",
    "ReportPeriod",
    "ChartConfig",
    "ReportData",
    "GeneratedReport",
    "ReportCallback",
    # Notification system
    "NotificationManager",
    "NotificationService",
    "NotificationPriority",
    "NotificationType",
    "MessageFormat",
    "TelegramConfig",
    "DiscordConfig",
    "NotificationConfig",
    "NotificationMessage",
    "NotificationResult",
    "NotificationStats",
    "TelegramNotifier",
    "DiscordNotifier",
    # Whale Bot System - Modular
    "WhaleBotCore",
    "MonitorCore",
    "WhaleDetectionEvent",
    
    # Intelligence
    "WhaleIntelligence",
    "IntelligenceEnhancements",
    "SocialSentimentAnalyzer",
    "SentimentScore",
    "SentimentAnomaly",
    
    # Analysis
    "MarketImpactAnalyzer",
    "SizeClassifier",
    "VolumeAnomalyDetector",
    "VolumeAnalyzer",
    "CorrelationEngine",
    
    # Tracking
    "CrossChainAnalytics",
    "AdvancedWhaleBot",
    "MLModelManager",
    
    # Risk & Strategy
    "AdvancedRiskManager",
    "StrategyAnalyzer",
    
    # Optimization
    "PortfolioOptimizer",
    
    # Integration
    "RealTimeDashboard",
    "DashboardIntegration",
    
    # Visualization (requires viz extras)
    "WhaleVolumeChart",
    "MarketImpactPlot", 
    "TradeDistributionChart",
    "PortfolioPerformanceChart",
    "SentimentAnalysisPlot",
    "CorrelationHeatmap",
    "RealTimeWhaleTracker",
    "TradingMetricsWidget",
    "AlertDistributionWidget",
    "PerformanceDashboard",
    "RealTimeChart",
    "ChartExporter",
    "HTMLReportGenerator",
    "PDFReportGenerator",
    "check_visualization_support",
    "get_recommended_installation",
    
    # Config
    "WhaleBotConfig",
    "Config",
    "load_whale_bot_config_from_env",
    "Phase3Config",
    "get_phase3_config",
    
    # Types
    "EnhancedTrade",
    "WhaleTier",
    "TradeUrgency",
    "FollowRecommendation",
    "WhalePattern",
    "MarketImpactAnalysis",
    "PredictionResult",
    "RiskAssessment",
    "BaseType",
]

# Optional imports - only loaded when specifically requested
def _optional_import(module_name):
    """Lazy import for optional modules"""
    try:
        module = __import__(f'hyperliquid_monitor_plus.{module_name}', fromlist=[module_name])
        return module
    except ImportError:
        return None

# Alert system (optional)
def _get_alerts():
    """Lazy import for alerts module"""
    module = _optional_import('alerts')
    if module:
        return module.AlertManager, module.AlertCondition, module.Alert, module.AlertLevel, module.AlertType, module.AlertCallback, module.TradeFilter, module.AlertFilter
    return None, None, None, None, None, None, None, None

# PnL system (optional)  
def _get_pnl():
    """Lazy import for PnL module"""
    module = _optional_import('pnl')
    if module:
        return module.PnLManager, module.PnLCalculator, module.Position, module.PnLRecord, module.CoinPnL, module.PortfolioPnL, module.PositionSide, module.PnLCallback
    return None, None, None, None, None, None, None, None

# Config system (optional)
def _get_config():
    """Lazy import for config module"""
    module = _optional_import('config')
    if module:
        return module.WhaleBotConfig, module.Config, module.load_whale_bot_config_from_env, module.Phase3Config, module.get_phase3_config
    return None, None, None, None, None

# Notifications system (optional)
def _get_notifications():
    """Lazy import for notifications module"""
    module = _optional_import('notifications')
    if module:
        return module.NotificationManager, module.NotificationService, module.NotificationPriority, module.NotificationType, module.MessageFormat, module.TelegramConfig, module.DiscordConfig, module.NotificationConfig, module.NotificationMessage, module.NotificationResult, module.NotificationStats, module.TelegramNotifier, module.DiscordNotifier
    return None, None, None, None, None, None, None, None, None, None, None, None

# Position tracking system (optional)
def _get_positions():
    """Lazy import for positions module"""
    module = _optional_import('positions')
    if module:
        return module.PositionTracker, module.LivePosition, module.PositionChange, module.PositionSnapshot, module.AccountState, module.PositionEventType, module.PositionChangeCallback, module.SnapshotCallback
    return None, None, None, None, None, None, None, None

# Strategy analysis system (optional)
def _get_strategy():
    """Lazy import for strategy module"""
    module = _optional_import('strategy')
    if module:
        return module.StrategyAnalyzer, module.StrategyMetrics, module.TradePattern, module.StrategyComparison, module.TimeAnalysis, module.StrategyRecommendation, module.PatternType, module.RecommendationType, module.AnalysisCallback
    return None, None, None, None, None, None, None, None, None

# Reporting system (optional)
def _get_reports():
    """Lazy import for reports module"""
    module = _optional_import('reports')
    if module:
        return module.ReportGenerator, module.ReportConfig, module.ReportFormat, module.ReportType, module.ReportPeriod, module.ChartConfig, module.ReportData, module.GeneratedReport, module.ReportCallback
    return None, None, None, None, None, None, None, None, None

# Intelligence system (optional)
def _get_intelligence():
    """Lazy import for intelligence module"""
    module = _optional_import('intelligence')
    if module:
        return module.WhaleIntelligence, module.IntelligenceEnhancements, module.SocialSentimentAnalyzer, module.SentimentScore, module.SentimentAnomaly
    return None, None, None, None, None

# Analysis system (optional)
def _get_analysis():
    """Lazy import for analysis module"""
    module = _optional_import('analysis')
    if module:
        return module.MarketImpactAnalyzer, module.SizeClassifier, module.VolumeAnomalyDetector, module.VolumeAnalyzer, module.CorrelationEngine
    return None, None, None, None, None

# Tracking system (optional)
def _get_tracking():
    """Lazy import for tracking module"""
    module = _optional_import('tracking')
    if module:
        return module.CrossChainAnalytics, module.AdvancedWhaleBot, module.MLModelManager
    return None, None, None

# Risk system (optional)
def _get_risk():
    """Lazy import for risk module"""
    module = _optional_import('risk')
    if module:
        return module.AdvancedRiskManager, module.StrategyAnalyzer
    return None, None

# Optimization system (optional)
def _get_optimization():
    """Lazy import for optimization module"""
    module = _optional_import('optimization')
    if module:
        return module.PortfolioOptimizer
    return None

# Integration system (optional)
def _get_integration():
    """Lazy import for integration module"""
    module = _optional_import('integration')
    if module:
        return module.RealTimeDashboard, module.DashboardIntegration
    return None, None