"""Contract tests: AuthZENBackend integrates with AGT PolicyEvaluator.

Verifies that authzen-policy-backend's AuthZENBackend (re-exported by
aria-agentkit's interceptor) works when registered with the real
PolicyEvaluator.add_backend() method.
"""

from __future__ import annotations

import httpx
import pytest
from agent_os.policies.backends import ExternalPolicyBackend
from agent_os.policies.evaluator import PolicyEvaluator
from authzen_backend import AuthZENBackend


@pytest.fixture
def pdp_backend() -> AuthZENBackend:
    def handler(request: httpx.Request) -> httpx.Response:
        return httpx.Response(
            status_code=200,
            json={"decision": True, "context": {"reason_admin": "allowed by test"}},
        )

    return AuthZENBackend(
        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 TestPolicyEvaluatorIntegration:
    def test_backend_satisfies_external_policy_backend(self, pdp_backend: AuthZENBackend) -> None:
        assert isinstance(pdp_backend, ExternalPolicyBackend)

    def test_add_backend_accepts_authzen(self, pdp_backend: AuthZENBackend) -> None:
        evaluator = PolicyEvaluator()
        evaluator.add_backend(pdp_backend)
        assert len(evaluator._backends) == 1

    def test_evaluate_calls_authzen_backend(self, pdp_backend: AuthZENBackend) -> None:
        evaluator = PolicyEvaluator()
        evaluator.add_backend(pdp_backend)
        decision = evaluator.evaluate(
            {
                "tool_name": "web_search",
                "agent_id": "agent-1",
            }
        )
        assert decision.allowed is True
