import pytest
from unittest.mock import MagicMock, patch
import os
import sys

# Ensure project root is in path
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))

from simulation.sim_context import ContextSimulation

def test_context_simulation_run():
    mock_client = MagicMock()
    mock_client.wait_for_server.return_value = True
    
    # Mock project config
    mock_project = {
        'project': {
            'files': {'paths': []}
        }
    }
    mock_client.get_project.return_value = mock_project
    mock_client.get_value.side_effect = lambda key: {
        "ai_status": "md written: test.md",
        "token_budget_pct": 0.05
    }.get(key)
    
    # Mock session entries
    mock_session = {
        'session': {
            'entries': [
                {'role': 'User', 'content': 'Hello'},
                {'role': 'AI', 'content': 'Hi'}
            ]
        }
    }
    mock_client.get_session.return_value = mock_session

    with patch('simulation.sim_base.WorkflowSimulator') as mock_sim_class:
        mock_sim = MagicMock()
        mock_sim_class.return_value = mock_sim
        
        sim = ContextSimulation(mock_client)
        sim.run()
        
        # Verify calls
        mock_sim.create_discussion.assert_called()
        mock_client.post_project.assert_called()
        mock_client.click.assert_called_with("btn_md_only")
        mock_sim.run_discussion_turn.assert_called()
        mock_sim.truncate_history.assert_called_with(1)
