#!/usr/bin/env python3
"""
Test script for UI fixes: connection counting, canvas cleanup, and global status bar.

Tests the latest improvements to the dashboard interface.
"""

import sys
import os

# Add parent directory to path
current_dir = os.path.dirname(os.path.abspath(__file__))
parent_dir = os.path.dirname(current_dir)
sys.path.insert(0, parent_dir)

def test_connection_counting():
    """Test improved connection counting logic."""
    print("🔍 Testing connection counting improvements...")
    
    try:
        from cluster4npu_ui.ui.windows.dashboard import IntegratedPipelineDashboard
        
        # Check if the updated analyze_pipeline method exists
        if hasattr(IntegratedPipelineDashboard, 'analyze_pipeline'):
            print("✅ analyze_pipeline method exists")
            
            # Read the source to verify improved connection counting
            import inspect
            source = inspect.getsource(IntegratedPipelineDashboard.analyze_pipeline)
            
            # Check for improved connection counting logic
            if 'output_ports' in source and 'connected_ports' in source:
                print("✅ Improved connection counting logic found")
            else:
                print("⚠️  Connection counting logic may need verification")
            
            # Check for error handling in connection counting
            if 'try:' in source and 'except Exception:' in source:
                print("✅ Error handling in connection counting")
            
        else:
            print("❌ analyze_pipeline method missing")
            return False
        
        return True
    except Exception as e:
        print(f"❌ Connection counting test failed: {e}")
        return False

def test_canvas_cleanup():
    """Test canvas cleanup (logo removal)."""
    print("\n🔍 Testing canvas cleanup...")
    
    try:
        from cluster4npu_ui.ui.windows.dashboard import IntegratedPipelineDashboard
        
        # Check if the setup_node_graph method has logo removal code
        if hasattr(IntegratedPipelineDashboard, 'setup_node_graph'):
            print("✅ setup_node_graph method exists")
            
            # Check source for logo removal logic
            import inspect
            source = inspect.getsource(IntegratedPipelineDashboard.setup_node_graph)
            
            if 'set_logo_visible' in source or 'show_logo' in source:
                print("✅ Logo removal logic found")
            else:
                print("⚠️  Logo removal logic may need verification")
            
            if 'set_grid_mode' in source or 'grid_mode' in source:
                print("✅ Grid mode configuration found")
            
        else:
            print("❌ setup_node_graph method missing")
            return False
        
        return True
    except Exception as e:
        print(f"❌ Canvas cleanup test failed: {e}")
        return False

def test_global_status_bar():
    """Test global status bar spanning full width."""
    print("\n🔍 Testing global status bar...")
    
    try:
        from cluster4npu_ui.ui.windows.dashboard import IntegratedPipelineDashboard
        
        # Check if setup_integrated_ui has global status bar
        if hasattr(IntegratedPipelineDashboard, 'setup_integrated_ui'):
            print("✅ setup_integrated_ui method exists")
            
            # Check source for global status bar
            import inspect
            source = inspect.getsource(IntegratedPipelineDashboard.setup_integrated_ui)
            
            if 'global_status_bar' in source:
                print("✅ Global status bar found")
            else:
                print("⚠️  Global status bar may need verification")
            
            if 'main_layout.addWidget' in source:
                print("✅ Status bar added to main layout")
            
        else:
            print("❌ setup_integrated_ui method missing")
            return False
        
        # Check if create_status_bar_widget exists
        if hasattr(IntegratedPipelineDashboard, 'create_status_bar_widget'):
            print("✅ create_status_bar_widget method exists")
            
            # Check source for full-width styling
            import inspect
            source = inspect.getsource(IntegratedPipelineDashboard.create_status_bar_widget)
            
            if 'border-top' in source and 'background-color' in source:
                print("✅ Full-width status bar styling found")
            
        else:
            print("❌ create_status_bar_widget method missing")
            return False
        
        return True
    except Exception as e:
        print(f"❌ Global status bar test failed: {e}")
        return False

def test_stage_count_widget_updates():
    """Test StageCountWidget updates for global status bar."""
    print("\n🔍 Testing StageCountWidget updates...")
    
    try:
        from cluster4npu_ui.ui.windows.dashboard import StageCountWidget
        from PyQt5.QtWidgets import QApplication
        
        app = QApplication.instance()
        if app is None:
            app = QApplication([])
        
        # Create widget
        widget = StageCountWidget()
        print("✅ StageCountWidget created successfully")
        
        # Test size for global status bar
        size = widget.size()
        if size.width() == 120 and size.height() == 22:
            print(f"✅ Correct size for global status bar: {size.width()}x{size.height()}")
        else:
            print(f"⚠️  Size may need adjustment: {size.width()}x{size.height()}")
        
        # Test status updates
        widget.update_stage_count(0, True, "")
        print("✅ Zero stages update test")
        
        widget.update_stage_count(2, True, "")
        print("✅ Valid stages update test")
        
        widget.update_stage_count(1, False, "Test error")
        print("✅ Error state update test")
        
        return True
    except Exception as e:
        print(f"❌ StageCountWidget test failed: {e}")
        return False

def test_layout_structure():
    """Test that the layout structure is correct."""
    print("\n🔍 Testing layout structure...")
    
    try:
        from cluster4npu_ui.ui.windows.dashboard import IntegratedPipelineDashboard
        
        # Check if create_pipeline_editor_panel no longer has status bar
        if hasattr(IntegratedPipelineDashboard, 'create_pipeline_editor_panel'):
            print("✅ create_pipeline_editor_panel method exists")
            
            # Check that it doesn't create its own status bar
            import inspect
            source = inspect.getsource(IntegratedPipelineDashboard.create_pipeline_editor_panel)
            
            if 'create_status_bar_widget' not in source:
                print("✅ Pipeline editor panel no longer creates its own status bar")
            else:
                print("⚠️  Pipeline editor panel may still create status bar")
            
        else:
            print("❌ create_pipeline_editor_panel method missing")
            return False
        
        return True
    except Exception as e:
        print(f"❌ Layout structure test failed: {e}")
        return False

def run_all_tests():
    """Run all UI fix tests."""
    print("🚀 Starting UI fixes tests...\n")
    
    tests = [
        test_connection_counting,
        test_canvas_cleanup,
        test_global_status_bar,
        test_stage_count_widget_updates,
        test_layout_structure
    ]
    
    passed = 0
    total = len(tests)
    
    for test_func in tests:
        try:
            if test_func():
                passed += 1
            else:
                print(f"❌ Test {test_func.__name__} failed")
        except Exception as e:
            print(f"❌ Test {test_func.__name__} raised exception: {e}")
    
    print(f"\n📊 Test Results: {passed}/{total} tests passed")
    
    if passed == total:
        print("🎉 All UI fixes tests passed!")
        print("\n📋 Summary of fixes:")
        print("   ✅ Connection counting improved to handle different port types")
        print("   ✅ Canvas logo/icon in bottom-left corner removed")
        print("   ✅ Status bar now spans full width across all panels")
        print("   ✅ StageCountWidget optimized for global status bar")
        print("   ✅ Layout structure cleaned up")
        return True
    else:
        print("❌ Some UI fixes tests failed.")
        return False

if __name__ == "__main__":
    success = run_all_tests()
    sys.exit(0 if success else 1)