from unittest.mock import patch

from ai_testing_swarm.agents.execution_agent import ExecutionAgent


class _FakeResponse:
    def __init__(self, status_code=200, payload=None):
        self.status_code = status_code
        self._payload = payload if payload is not None else {"ok": True}
        self.text = str(self._payload)

    def json(self):
        return self._payload


def test_root_replace_mutation_applies_for_headers():
    agent = ExecutionAgent()
    request = {
        "method": "POST",
        "url": "https://example.com",
        "headers": {"Authorization": "Bearer abc"},
        "params": {},
        "body": {"x": 1},
    }
    test_case = {
        "name": "headers_empty",
        "mutation": {
            "target": "headers",
            "path": [],
            "operation": "REPLACE",
            "new_value": {},
        },
    }

    with patch("ai_testing_swarm.agents.execution_agent.requests.request", return_value=_FakeResponse()) as mock_req:
        result = agent.execute(request, test_case)

    assert result["request"]["headers"] == {}
    assert mock_req.call_args.kwargs["headers"] == {}


def test_root_remove_mutation_applies_for_query():
    agent = ExecutionAgent()
    request = {
        "method": "GET",
        "url": "https://example.com",
        "headers": {},
        "params": {"q": "desk"},
        "body": {},
    }
    test_case = {
        "name": "query_clear",
        "mutation": {
            "target": "query",
            "path": [],
            "operation": "REMOVE",
        },
    }

    with patch("ai_testing_swarm.agents.execution_agent.requests.request", return_value=_FakeResponse()) as mock_req:
        result = agent.execute(request, test_case)

    assert result["request"]["params"] == {}
    assert mock_req.call_args.kwargs["params"] is None
