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

@pytest.fixture
def app_instance():
    with (
        patch('gui_2.load_config', return_value={'ai': {'provider': 'gemini', 'model': 'gemini-2.5-flash-lite'}, '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'),
        patch('ai_client.set_provider'),
        patch('ai_client.reset_session')
    ):
        app = App()
        yield app

def test_redundant_calls_in_process_pending_gui_tasks(app_instance):
    # Setup
    app_instance._pending_gui_tasks = [
        {'action': 'set_value', 'item': 'current_provider', 'value': 'anthropic'}
    ]
    
    with patch('ai_client.set_provider') as mock_set_provider, 
         patch('ai_client.reset_session') as mock_reset_session:
        
        # We need to make sure the property setter's internal calls are also tracked or mocked.
        # However, the App instance was created with mocked ai_client.
        # Let's re-patch it specifically for this test.
        
        app_instance._process_pending_gui_tasks()
        
        # current_provider setter calls:
        # ai_client.reset_session()
        # ai_client.set_provider(value, self.current_model)
        
        # _process_pending_gui_tasks ALSO calls:
        # ai_client.set_provider(self.current_provider, self.current_model)
        # ai_client.reset_session()
        
        # Total should be 2 calls for each if redundant.
        assert mock_set_provider.call_count == 2
        assert mock_reset_session.call_count == 2

def test_gcli_path_updates_adapter(app_instance):
    # Setup
    app_instance.current_provider = 'gemini_cli'
    app_instance._pending_gui_tasks = [
        {'action': 'set_value', 'item': 'gcli_path', 'value': '/new/path/to/gemini'}
    ]
    
    # Initialize adapter if it doesn't exist (it shouldn't in mock env)
    ai_client._gemini_cli_adapter = None
    
    app_instance._process_pending_gui_tasks()
    
    assert ai_client._gemini_cli_adapter is not None
    assert ai_client._gemini_cli_adapter.binary_path == '/new/path/to/gemini'
