"""
Patch for the MainWindow class to use EnhancedVideoController by default.
This file is imported by main.py to modify MainWindow's behavior.
"""

# Import all necessary Qt components
from PySide6.QtCore import Qt, QTimer
from PySide6.QtWidgets import QMessageBox

# Import the enhanced controller - handle potential import errors
try:
    from controllers.enhanced_video_controller import EnhancedVideoController
except ImportError:
    try:
        from qt_app_pyside.controllers.enhanced_video_controller import EnhancedVideoController
    except ImportError:
        print("⚠️ Warning: Could not import EnhancedVideoController. Using fallback controller.")
        EnhancedVideoController = None

# Original imports preserved for compatibility - handle potential import errors
try:
    from controllers.video_controller_new import VideoController
    from controllers.analytics_controller import AnalyticsController
    from controllers.performance_overlay import PerformanceOverlay
    from controllers.model_manager import ModelManager
except ImportError:
    try:
        from qt_app_pyside.controllers.video_controller_new import VideoController
        from qt_app_pyside.controllers.analytics_controller import AnalyticsController
        from qt_app_pyside.controllers.performance_overlay import PerformanceOverlay
        from qt_app_pyside.controllers.model_manager import ModelManager
    except ImportError:
        print("⚠️ Warning: Could not import controller modules.")

# Store original method reference
original_setup_controllers = None

def enhanced_setup_controllers(self):
    """Enhanced version of setupControllers that uses the EnhancedVideoController"""
    global EnhancedVideoController, ModelManager, AnalyticsController
    
    # If modules couldn't be imported, fall back to original method
    if EnhancedVideoController is None:
        print("⚠️ Enhanced controller not available, falling back to original setup")
        if original_setup_controllers:
            original_setup_controllers(self)
        return
    
    # Store existing source if video controller already exists
    existing_source = None
    if hasattr(self, 'video_controller') and self.video_controller:
        # Grab the current source before replacing the controller
        print("📽️ Preserving existing video source...")
        try:
            # Try to get source from the processing thread
            if hasattr(self.video_controller, 'processing_thread') and self.video_controller.processing_thread:
                existing_source = self.video_controller.processing_thread.source
                print(f"✅ Preserved source from processing thread: {existing_source}")
            # Backup: Get source directly from live tab
            elif hasattr(self, 'live_tab') and hasattr(self.live_tab, 'current_source'):
                existing_source = self.live_tab.current_source
                print(f"✅ Preserved source from live tab: {existing_source}")
        except Exception as e:
            print(f"⚠️ Could not preserve source: {e}")
    
    # Load config from file
    try:        # Initialize model manager
        self.model_manager = ModelManager(self.config_file)
        
        # Create enhanced video controller instead of regular one
        print("🚀 Creating enhanced video controller with async inference...")
        self.video_controller = EnhancedVideoController(self.model_manager)
        
        # Restore the source if we had one or check the live tab
        # First try the source we grabbed earlier
        if existing_source is not None and existing_source != 0:
            print(f"🔄 Restoring video source from previous controller: {existing_source}")
            self.video_controller.set_source(existing_source)
        # If we couldn't get it from the previous controller, try getting it from the live tab directly
        elif hasattr(self, 'live_tab') and hasattr(self.live_tab, 'current_source') and self.live_tab.current_source is not None and self.live_tab.current_source != 0:
            print(f"🔄 Using source directly from live_tab: {self.live_tab.current_source}")
            self.video_controller.set_source(self.live_tab.current_source)
        
        # Create analytics controller
        self.analytics_controller = AnalyticsController()
        
        # Setup update timer for performance overlay
        self.perf_timer = QTimer()
        self.perf_timer.timeout.connect(self.performance_overlay.update_stats)
        self.perf_timer.start(1000)  # Update every second
        
        # Important: Do NOT set a default source - let the UI handle it properly
        # This allows video files to be loaded and remembered
        
        print("✅ Enhanced controller setup complete!")
        
    except Exception as e:
        # Show error message
        from PySide6.QtWidgets import QMessageBox
        QMessageBox.critical(
            self, 
            "Initialization Error", 
            f"Error initializing enhanced controllers: {str(e)}"
        )            
        print(f"❌ Error details: {e}")
        # Fall back to original method if there's an error
        if original_setup_controllers:
            print("⚠️ Falling back to original controller setup")
            original_setup_controllers(self)

# Function to patch the MainWindow class and return the patched version
def patch_mainwindow_class():
    """
    Import and patch the MainWindow class to use EnhancedVideoController by default.
    Returns the patched MainWindow class.
    """
    global original_setup_controllers
    
    # Import MainWindow here to avoid circular imports
    from ui.main_window import MainWindow
    
    # Store the original method
    original_setup_controllers = MainWindow.setupControllers
    
    # Replace with enhanced method
    MainWindow.setupControllers = enhanced_setup_controllers
    
    print("✅ MainWindow patched to use EnhancedVideoController")
    
    return MainWindow
