import pytest
from unittest.mock import MagicMock, patch
from gui_2 import App
import ai_client
from events import EventEmitter

@pytest.fixture
def app_instance():
    """
    Fixture to create an instance of the gui_2.App class for testing.
    It mocks functions that would render a window or block execution.
    """
    if not hasattr(ai_client, 'events') or ai_client.events is None:
        ai_client.events = EventEmitter()

    with (
        patch('gui_2.load_config', return_value={'ai': {}, 'projects': {}}),
        patch('gui_2.save_config'),
        patch('gui_2.project_manager'),
        patch('gui_2.session_logger'),
        patch('gui_2.immapp.run'),
        patch.object(App, '_load_active_project'),
        patch.object(App, '_fetch_models'),
        patch.object(App, '_load_fonts'),
        patch.object(App, '_post_init')
    ):
        yield App

def test_app_subscribes_to_events(app_instance):
    """
    This test checks that the App's __init__ method subscribes the necessary
    event handlers to the ai_client.events emitter.
    This test will fail until the event subscription logic is added to gui_2.App.
    """
    with patch.object(ai_client.events, 'on') as mock_on:
        app = app_instance()
        mock_on.assert_called()
        
        calls = mock_on.call_args_list
        event_names = [call.args[0] for call in calls]
        assert "request_start" in event_names
        assert "response_received" in event_names
        assert "tool_execution" in event_names

        for call in calls:
            handler = call.args[1]
            assert hasattr(handler, '__self__')
            assert handler.__self__ is app
