#!/usr/bin/env python3
"""
Test script for status bar fixes: stage count display and UI cleanup.

Tests the fixes for stage count visibility and NodeGraphQt UI cleanup.
"""

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_stage_count_visibility():
    """Test stage count widget visibility and updates."""
    print("🔍 Testing stage count widget visibility...")
    
    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 visibility
        if widget.isVisible():
            print("✅ Widget is visible")
        else:
            print("❌ Widget is not visible")
            return False
        
        if widget.stage_label.isVisible():
            print("✅ Stage label is visible")
        else:
            print("❌ Stage label is not visible")
            return False
        
        # Test size
        size = widget.size()
        if size.width() == 120 and size.height() == 22:
            print(f"✅ Correct size: {size.width()}x{size.height()}")
        else:
            print(f"⚠️  Size: {size.width()}x{size.height()}")
        
        # Test font size
        font = widget.stage_label.font()
        if font.pointSize() == 10:
            print(f"✅ Font size: {font.pointSize()}pt")
        else:
            print(f"⚠️  Font size: {font.pointSize()}pt")
        
        return True
    except Exception as e:
        print(f"❌ Stage count visibility test failed: {e}")
        return False

def test_stage_count_updates():
    """Test stage count widget updates with different states."""
    print("\n🔍 Testing stage count updates...")
    
    try:
        from cluster4npu_ui.ui.windows.dashboard import StageCountWidget
        from PyQt5.QtWidgets import QApplication
        
        app = QApplication.instance()
        if app is None:
            app = QApplication([])
        
        widget = StageCountWidget()
        
        # Test zero stages (warning state)
        widget.update_stage_count(0, True, "")
        if "⚠️" in widget.stage_label.text():
            print("✅ Zero stages warning display")
        else:
            print(f"⚠️  Zero stages text: {widget.stage_label.text()}")
        
        # Test valid stages (success state)
        widget.update_stage_count(2, True, "")
        if "✅" in widget.stage_label.text() and "2" in widget.stage_label.text():
            print("✅ Valid stages success display")
        else:
            print(f"⚠️  Valid stages text: {widget.stage_label.text()}")
        
        # Test error state
        widget.update_stage_count(1, False, "Test error")
        if "❌" in widget.stage_label.text():
            print("✅ Error state display")
        else:
            print(f"⚠️  Error state text: {widget.stage_label.text()}")
        
        return True
    except Exception as e:
        print(f"❌ Stage count updates test failed: {e}")
        return False

def test_ui_cleanup_functionality():
    """Test UI cleanup functionality."""
    print("\n🔍 Testing UI cleanup functionality...")
    
    try:
        from cluster4npu_ui.ui.windows.dashboard import IntegratedPipelineDashboard
        
        # Check if cleanup method exists
        if hasattr(IntegratedPipelineDashboard, 'cleanup_node_graph_ui'):
            print("✅ cleanup_node_graph_ui method exists")
        else:
            print("❌ cleanup_node_graph_ui method missing")
            return False
        
        # Check if setup includes cleanup timer
        import inspect
        source = inspect.getsource(IntegratedPipelineDashboard.__init__)
        if 'ui_cleanup_timer' in source:
            print("✅ UI cleanup timer setup found")
        else:
            print("⚠️  UI cleanup timer setup not found")
        
        # Check cleanup method implementation
        source = inspect.getsource(IntegratedPipelineDashboard.cleanup_node_graph_ui)
        if 'bottom-left' in source and 'setVisible(False)' in source:
            print("✅ Cleanup method has bottom-left widget hiding logic")
        else:
            print("⚠️  Cleanup method logic may need verification")
        
        return True
    except Exception as e:
        print(f"❌ UI cleanup test failed: {e}")
        return False

def test_status_bar_integration():
    """Test status bar integration."""
    print("\n🔍 Testing status bar integration...")
    
    try:
        from cluster4npu_ui.ui.windows.dashboard import IntegratedPipelineDashboard
        
        # Check if create_status_bar_widget exists
        if hasattr(IntegratedPipelineDashboard, 'create_status_bar_widget'):
            print("✅ create_status_bar_widget method exists")
        else:
            print("❌ create_status_bar_widget method missing")
            return False
        
        # Check if setup_integrated_ui includes global status bar
        import inspect
        source = inspect.getsource(IntegratedPipelineDashboard.setup_integrated_ui)
        if 'global_status_bar' in source:
            print("✅ Global status bar integration found")
        else:
            print("❌ Global status bar integration missing")
            return False
        
        # Check if analyze_pipeline has debug output
        source = inspect.getsource(IntegratedPipelineDashboard.analyze_pipeline)
        if 'Updating stage count widget' in source:
            print("✅ Debug output for stage count updates found")
        else:
            print("⚠️  Debug output not found")
        
        return True
    except Exception as e:
        print(f"❌ Status bar integration test failed: {e}")
        return False

def test_node_graph_configuration():
    """Test node graph configuration for UI cleanup."""
    print("\n🔍 Testing node graph configuration...")
    
    try:
        from cluster4npu_ui.ui.windows.dashboard import IntegratedPipelineDashboard
        
        # Check if setup_node_graph has UI cleanup code
        import inspect
        source = inspect.getsource(IntegratedPipelineDashboard.setup_node_graph)
        
        cleanup_checks = [
            'set_logo_visible',
            'set_nav_widget_visible',
            'set_minimap_visible',
            'findChildren',
            'setVisible(False)'
        ]
        
        found_cleanup = []
        for check in cleanup_checks:
            if check in source:
                found_cleanup.append(check)
        
        if len(found_cleanup) >= 3:
            print(f"✅ UI cleanup code found: {', '.join(found_cleanup)}")
        else:
            print(f"⚠️  Limited cleanup code found: {', '.join(found_cleanup)}")
        
        return True
    except Exception as e:
        print(f"❌ Node graph configuration test failed: {e}")
        return False

def run_all_tests():
    """Run all status bar fix tests."""
    print("🚀 Starting status bar fixes tests...\n")
    
    tests = [
        test_stage_count_visibility,
        test_stage_count_updates,
        test_ui_cleanup_functionality,
        test_status_bar_integration,
        test_node_graph_configuration
    ]
    
    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 status bar fixes tests passed!")
        print("\n📋 Summary of fixes:")
        print("   ✅ Stage count widget visibility improved")
        print("   ✅ Stage count updates with proper status icons")
        print("   ✅ UI cleanup functionality for NodeGraphQt elements")
        print("   ✅ Global status bar integration")
        print("   ✅ Node graph configuration for UI cleanup")
        print("\n💡 The fixes should resolve:")
        print("   • Stage count not displaying in status bar")
        print("   • Left-bottom corner horizontal bar visibility")
        return True
    else:
        print("❌ Some status bar fixes tests failed.")
        return False

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