"""Contract tests: ARIAToolInterceptor satisfies ToolCallInterceptor Protocol.

These tests import real AGT types from agent-os-kernel to verify
structural compatibility.
"""

from __future__ import annotations

import httpx
import pytest
from agent_os.integrations.base import (
    ToolCallRequest,
    ToolCallResult,
)

from aria_agentkit.policy.interceptor import ARIAToolInterceptor


@pytest.fixture
def interceptor() -> ARIAToolInterceptor:
    def handler(request: httpx.Request) -> httpx.Response:
        return httpx.Response(status_code=200, json={"decision": True})

    return ARIAToolInterceptor(
        pdp_url="http://localhost:8001/access/v1/evaluation",
        pdp_application="contract-test",
        token="test-token",
        http_client=httpx.Client(transport=httpx.MockTransport(handler)),
    )


@pytest.mark.contract
class TestInterceptorProtocol:
    def test_has_intercept_method(self, interceptor: ARIAToolInterceptor) -> None:
        """ToolCallInterceptor Protocol requires intercept() method."""
        assert hasattr(interceptor, "intercept")
        assert callable(interceptor.intercept)

    def test_intercept_returns_tool_call_result(self, interceptor: ARIAToolInterceptor) -> None:
        result = interceptor.intercept(
            ToolCallRequest(
                tool_name="test_tool",
                arguments={"x": 1},
                call_id="c1",
                agent_id="a1",
            )
        )
        assert isinstance(result, ToolCallResult)

    def test_result_has_required_fields(self, interceptor: ARIAToolInterceptor) -> None:
        result = interceptor.intercept(
            ToolCallRequest(
                tool_name="t",
                arguments={},
                agent_id="a",
            )
        )
        assert hasattr(result, "allowed")
        assert hasattr(result, "reason")
        assert hasattr(result, "modified_arguments")
        assert hasattr(result, "audit_entry")

    def test_authzen_request_is_sent_directly(self, interceptor: ARIAToolInterceptor) -> None:
        """The interceptor must POST *our* AuthZEN mapping, not a re-mapped version."""
        result = interceptor.intercept(
            ToolCallRequest(
                tool_name="web_search",
                arguments={"q": "test"},
                call_id="c-wire",
                agent_id="agent-1",
            )
        )
        entry = result.audit_entry
        assert entry is not None
        req = entry["authzen_request"]
        assert req["action"]["name"] == "tool.invoke"
        assert req["resource"]["type"] == "mcp_tool"
        assert "agent-1" in req["subject"]["id"]
