from pathlib import Path
import pytest

from agent_framework.guardrails.base import RailDecision
from agent_framework.guardrails.output_supervisor import OutputSupervisor
from agent_framework.guardrails.rail_action import RailAction


class RetryByMetadataRail:
    code = "ANY_POLICY_RAIL"
    async def evaluate(self, text, context):
        return RailDecision(code=self.code, allowed=False, reason="retry me", metadata={"terminal_action": "retry"})


class RewriteByMetadataRail:
    code = "ANY_WORDING_RAIL"
    def __init__(self): self.calls = 0
    async def evaluate(self, text, context):
        self.calls += 1
        blocked = self.calls == 1
        return RailDecision(
            code=self.code, allowed=not blocked, reason="wording" if blocked else "",
            sanitized_text=text,
            metadata={"remediation": {"type":"rewrite", "max_attempts":1, "prompt_id":"FALLBACK"}},
        )


@pytest.mark.asyncio
async def test_retry_is_driven_by_metadata_not_rail_name():
    sup = OutputSupervisor(rails=[RetryByMetadataRail()], enable_parallel=False)
    decision = await sup.evaluate("x", {})
    assert decision.action == RailAction.RETRY


@pytest.mark.asyncio
async def test_rewrite_is_driven_by_remediation_metadata(monkeypatch):
    rail = RewriteByMetadataRail()
    async def fake(*args, **kwargs):
        return {"reason": "rewritten"}
    monkeypatch.setattr("agent_framework.guardrails.output_supervisor.classify_with_framework_llm", fake)
    sup = OutputSupervisor(rails=[rail], enable_parallel=False, llm=object())
    decision = await sup.evaluate("original", {})
    assert decision.candidate == "rewritten"
    assert decision.metadata["guardrail_rewritten"] is True
    assert decision.metadata["guardrail_rewrite_code"] == "ANY_WORDING_RAIL"
    assert any(r.code == "ANY_WORDING_RAIL_REWRITE" for r in decision.results)


def test_output_supervisor_contains_no_customer_grl_taxonomy_or_named_policy_switches():
    path = Path(__file__).parents[2] / "agent_framework_oci/libs/agent_framework/src/agent_framework/guardrails/output_supervisor.py"
    text = path.read_text(encoding="utf-8")
    assert "GRL.001" not in text
    assert "GRL.004" not in text
    assert "GRL.009" not in text
    assert 'code in {"REVPREC"' not in text
    assert '== "FRASEOLOGIA"' not in text
