"""
Update main window to use enhanced video controller with async inference.
This module provides functions to inject optimized controllers into an existing Qt app.
"""

import sys
import os
import time
from pathlib import Path

# Add parent directory to path
parent_dir = Path(__file__).parent.parent
if str(parent_dir) not in sys.path:
    sys.path.append(str(parent_dir))

# These imports will work when the script is run inside the Qt app
try:
    from PySide6.QtWidgets import QApplication, QMessageBox, QTabWidget, QWidget
    from PySide6.QtCore import Qt
    # Import our enhanced controller
    from controllers.enhanced_video_controller import EnhancedVideoController
    from controllers.model_manager import ModelManager
except ImportError:
    # For linting/development outside the app
    print("Note: PySide6 imports not available outside of Qt app environment")

def update_main_window():
    """
    Update main window to use enhanced video controller with async inference.
    
    This function finds the running MainWindow instance and injects our enhanced
    video controller with async inference support.
    """
    try:
        print("\n" + "="*80)
        print("Enhancing Video Controller with Async Inference")
        print("="*80)
        
        # Find the Qt application instance
        app = QApplication.instance()
        if not app:
            print("❌ QApplication instance not found!")
            return False
        
        # Find main window instance
        for widget in app.topLevelWidgets():
            if widget.__class__.__name__ == "MainWindow":
                main_window = widget
                break
        else:
            print("❌ Main window not found!")
            return False
            
        # Find the tab widget and live tab
        tab_widget = None
        for child in main_window.children():
            if isinstance(child, QTabWidget):
                tab_widget = child
                break
                
        if not tab_widget:
            print("❌ Tab widget not found!")
            return False
            
        # Find live tab
        live_tab = None
        for i in range(tab_widget.count()):
            if tab_widget.tabText(i).lower() == "live":
                live_tab = tab_widget.widget(i)
                break
                
        if not live_tab:
            print("❌ Live tab not found!")
            return False            
        # Get the configuration panel to read current device and model settings
        config_panel = None
        for widget in main_window.findChildren(QWidget):
            if widget.__class__.__name__ == "ConfigPanel":
                config_panel = widget
                break
                
        # Initialize the model manager with optimized settings for CPU
        model_manager = ModelManager()
        
        # Update model manager with best model for CPU
        if config_panel:
            # Get the device selection from config panel
            device_combo = None
            for child in config_panel.children():
                if hasattr(child, 'currentText') and child.objectName() == "device_combo":
                    device_combo = child
                    break
                    
            if device_combo:
                print(f"✅ Found device selection: current = {device_combo.currentText()}")
                # Make sure CPU is selected when on CPU hardware
                if device_combo.currentText() != "CPU":
                    print("⚠️ Switching to CPU for optimal performance...")
                    device_combo.setCurrentText("CPU")
                
                # Force update config
                if hasattr(config_panel, 'apply_config'):
                    config_panel.apply_config()
        
        # Create enhanced video controller with async support
        print("🚀 Creating enhanced video controller with async inference...")
        enhanced_controller = EnhancedVideoController(model_manager)
        
        # Find the frame display widget (might have different names in different implementations)
        frame_display = None
        for widget in live_tab.findChildren(QWidget):
            if hasattr(widget, 'display_frame'):
                frame_display = widget
                break
                
        if not frame_display:
            print("⚠️ Frame display widget not found by method. Searching by common names...")
            for name in ["frame_display", "liveDisplay", "videoDisplay"]:
                widget = live_tab.findChild(QWidget, name)
                if widget and hasattr(widget, 'display_frame'):
                    frame_display = widget
                    break
        
        if frame_display:
            print(f"✅ Found frame display widget: {frame_display}")
            enhanced_controller.frame_ready.connect(frame_display.display_frame)
        else:
            print("❌ Could not find frame display widget!")
            return False        # Get current source if available, otherwise use default camera
        if hasattr(live_tab, 'current_source') and live_tab.current_source is not None:
            print(f"✅ Using existing source from live_tab: {live_tab.current_source}")
            # Check if it's a file path and if it exists
            if isinstance(live_tab.current_source, str) and os.path.exists(live_tab.current_source):
                print(f"🎥 Setting video file source: {live_tab.current_source}")
                enhanced_controller.set_source(live_tab.current_source)
            elif live_tab.current_source != 0:
                print(f"🎥 Setting non-default source: {live_tab.current_source}")
                enhanced_controller.set_source(live_tab.current_source)
            else:
                print("⚠️ Source is default camera (0)")
                enhanced_controller.set_source(0)
        else:
            # Check if there's a video source combo box
            source_combo = None
            for child in live_tab.children():
                if hasattr(child, 'currentData') and child.objectName() == "source_combo":
                    source_combo = child
                    break
                    
            if source_combo and source_combo.currentData() == "file":
                print("⚠️ File source selected but no file path found. Prompting user...")
                # Try to open file dialog
                if hasattr(live_tab, 'browse_files'):
                    print("🔍 Calling browse_files()")
                    QTimer.singleShot(500, live_tab.browse_files)  # Open file dialog after UI is ready
                else:
                    print("⚠️ No source found, using default camera")
                    enhanced_controller.set_source(0)
            else:
                print("⚠️ No source found, using default camera")
                enhanced_controller.set_source(0)
        
        # Stop old controller if it exists
        if hasattr(live_tab, "video_controller") and live_tab.video_controller:
            print("⏹️ Stopping old video controller...")
            try:
                live_tab.video_controller.stop()
            except Exception as e:
                print(f"⚠️ Error stopping old controller: {e}")
                
        # Replace with enhanced controller
        live_tab.video_controller = enhanced_controller
              # Start the enhanced controller
        print("▶️ Starting enhanced video controller...")
        enhanced_controller.start()
        
        # Show success message
        print("✅ Enhanced video controller successfully activated!")
        QMessageBox.information(
            main_window,
            "Enhanced Video Processing",
            "Enhanced video controller with async inference activated!\n\n"
            "✅ Using FP16 precision for optimal CPU performance\n"
            "✅ Async inference pipeline activated\n"
            "✅ UI and detection FPS are now tracked separately\n"
            "✅ Automatic model selection based on device\n"
            "✅ OpenVINO embedder for DeepSORT tracking"
        )
        
        return True
        
    except Exception as e:
        print(f"❌ Error updating main window: {e}")
        import traceback
        traceback.print_exc()
        return False

def main():
    """
    Run this script from within the Qt app to inject our enhanced controller.
    """
    success = update_main_window()
    if success:
        print("✅ Update completed successfully!")
    else:
        print("❌ Update failed!")
    return success

if __name__ == "__main__":
    main()
