import pytest

from agent_framework.guardrails.rails import LoopRail


@pytest.mark.asyncio
async def test_vloop_allows_repeated_reply_while_transaction_awaits_confirmation():
    rail = LoopRail()
    decision = await rail.evaluate(
        "sim",
        {
            "transaction_status": "AWAITING_CONFIRMATION",
            "history_texts": ["sim", "outra fala", "sim"],
        },
    )
    assert decision.allowed is True
    assert decision.metadata["mechanism"] == "deterministic_transaction_bypass"
    assert decision.metadata["transaction_status"] == "AWAITING_CONFIRMATION"


@pytest.mark.asyncio
async def test_vloop_reads_awaiting_confirmation_from_active_transaction():
    rail = LoopRail()
    decision = await rail.evaluate(
        "sim",
        {
            "active_transaction": {"status": "AWAITING_CONFIRMATION"},
            "history_texts": ["sim", "sim"],
        },
    )
    assert decision.allowed is True
    assert decision.metadata["mechanism"] == "deterministic_transaction_bypass"


@pytest.mark.asyncio
async def test_vloop_still_blocks_actual_repetition_outside_transaction_confirmation():
    rail = LoopRail()
    decision = await rail.evaluate(
        "sim",
        {
            "transaction_status": None,
            "history_texts": ["sim", "outra fala", "sim"],
        },
    )
    assert decision.allowed is False
    assert decision.reason == "Possível loop conversacional"
    assert decision.metadata["repeated"] is True
