import pytest
from unittest.mock import patch, MagicMock
import importlib.util
import sys
import dearpygui.dearpygui as dpg

# Load gui.py as a module for testing
spec = importlib.util.spec_from_file_location("gui_legacy", "gui_legacy.py")
gui_legacy = importlib.util.module_from_spec(spec)
sys.modules["gui_legacy"] = gui_legacy
spec.loader.exec_module(gui_legacy)
from gui_legacy import App

@pytest.fixture
def app_instance():
    dpg.create_context()
    with patch('dearpygui.dearpygui.create_viewport'), \
         patch('dearpygui.dearpygui.setup_dearpygui'), \
         patch('dearpygui.dearpygui.show_viewport'), \
         patch('dearpygui.dearpygui.start_dearpygui'), \
         patch('gui_legacy.load_config', return_value={}), \
         patch.object(App, '_rebuild_files_list'), \
         patch.object(App, '_rebuild_shots_list'), \
         patch.object(App, '_rebuild_disc_list'), \
         patch.object(App, '_rebuild_disc_roles_list'), \
         patch.object(App, '_rebuild_discussion_selector'), \
         patch.object(App, '_refresh_project_widgets'):
        
        app = App()
        yield app
    dpg.destroy_context()

def test_diagnostics_panel_initialization(app_instance):
    assert "Diagnostics" in app_instance.window_info
    assert app_instance.window_info["Diagnostics"] == "win_diagnostics"
    assert "frame_time" in app_instance.perf_history
    assert len(app_instance.perf_history["frame_time"]) == 100

def test_diagnostics_panel_updates(app_instance):
    # Mock dependencies
    mock_metrics = {
        'last_frame_time_ms': 10.0,
        'fps': 100.0,
        'cpu_percent': 50.0,
        'input_lag_ms': 5.0
    }
    app_instance.perf_monitor.get_metrics = MagicMock(return_value=mock_metrics)
    
    with patch('dearpygui.dearpygui.is_item_shown', return_value=True), \
         patch('dearpygui.dearpygui.set_value') as mock_set_value, \
         patch('dearpygui.dearpygui.configure_item') as mock_configure_item, \
         patch('dearpygui.dearpygui.does_item_exist', return_value=True):
        
        # We also need to mock ai_client stats
        with patch('ai_client.get_history_bleed_stats', return_value={}):
            app_instance._update_performance_diagnostics()
            
            # Verify UI updates
            mock_set_value.assert_any_call("perf_fps_text", "100.0")
            mock_set_value.assert_any_call("perf_frame_text", "10.0ms")
            mock_set_value.assert_any_call("perf_cpu_text", "50.0%")
            mock_set_value.assert_any_call("perf_lag_text", "5.0ms")
            
            # Verify history update
            assert app_instance.perf_history["frame_time"][-1] == 10.0
