import requests
from copy import deepcopy


class ExecutionAgent:
    def apply_mutation(self, data: dict, mutation: dict):
        if not mutation:
            return deepcopy(data)

        data = deepcopy(data)
        key = mutation["path"][0]
        op = mutation["operation"]

        if op == "REMOVE":
            data.pop(key, None)
        elif op == "REPLACE":
            data[key] = mutation["new_value"]

        return data

    def execute(self, request: dict, test: dict):
        mutation = test.get("mutation")

        params = (
            self.apply_mutation(request.get("params", {}), mutation)
            if mutation and mutation.get("target") == "query"
            else deepcopy(request.get("params", {}))
        )

        body = (
            self.apply_mutation(request.get("body", {}), mutation)
            if mutation and mutation.get("target") == "body"
            else deepcopy(request.get("body", {}))
        )

        response = requests.request(
            method=request["method"],
            url=request["url"],
            headers=request["headers"],
            params=params or None,
            json=None if request["method"] == "GET" else body,
            timeout=10,
        )

        try:
            body_snippet = response.json()
        except Exception:
            body_snippet = response.text

        return {
            "name": test["name"],  # 🔥 CANONICAL
            "mutation": mutation,
            "request": {
                "method": request["method"],
                "url": request["url"],
                "headers": request["headers"],
                "params": params,
                "body": body if request["method"] != "GET" else None,
            },
            "response": {
                "status_code": response.status_code,
                "body_snippet": body_snippet,
            },
        }
