import importlib

import pytest

from app.agents.runtime import AgentRuntimeMixin


class _Runtime(AgentRuntimeMixin):
    def _tool_config(self, tool_name):
        return None

    def _resolve_tool_execution_policy(self, tool_name, arguments=None):
        return {"requires": ["subject"]}


def test_set_active_transaction_replaces_previous_terminal_scalar_status():
    runtime = _Runtime()
    state = {
        "transaction_status": "COMPLETED",
        "intent": "contas_vas_cancel",
        "active_transaction": None,
    }

    tx = runtime._set_active_transaction(
        state,
        tool_name="cancelar_vas_avulso",
        arguments={"subject": "TIM Fashion Mensal"},
        status="AWAITING_CONFIRMATION",
    )

    assert tx["status"] == "AWAITING_CONFIRMATION"
    assert state["active_transaction"]["tool_name"] == "cancelar_vas_avulso"
    assert state["transaction_status"] == "AWAITING_CONFIRMATION"

    # The next-turn lifecycle normalization must preserve the newly installed
    # transaction instead of treating the previous COMPLETED status as current.
    runtime._normalize_transaction_lifecycle(state)
    assert state["transaction_status"] == "AWAITING_CONFIRMATION"
    assert state["active_transaction"]["tool_name"] == "cancelar_vas_avulso"


def test_strategic_preflight_does_not_reresolve_prevalidated_subject(monkeypatch):
    mcp = importlib.import_module("contas_mcp.servers.contas_mcp_server.main")

    def _unexpected(*args, **kwargs):
        raise AssertionError("invoice resolver must not run for a prevalidated strategic subject")

    monkeypatch.setattr(mcp.invoice_resolver, "resolve", _unexpected)
    result = mcp._preflight_subject(
        "tratar_vas_estrategico",
        {
            "msisdn": "11999999999",
            "subject": "Aya Audiobooks Premium",
            "_vas_subject_prevalidated": True,
            "type": "bundle",
        },
    )
    assert result is None


@pytest.mark.asyncio
async def test_vas_validator_marks_resolved_subject_for_effective_tool(monkeypatch):
    mcp = importlib.import_module("contas_mcp.servers.contas_mcp_server.main")

    async def _noop_enrich(name, args):
        return None

    monkeypatch.setattr(mcp, "_enrich_invoice_context", _noop_enrich)
    monkeypatch.setattr(mcp, "_vas_entity_catalog", lambda args: [{"name": "Aya Audiobooks Premium"}])
    monkeypatch.setattr(mcp, "_resolve_catalog_entity", lambda subject, catalog: ("Aya Audiobooks Premium", []))
    monkeypatch.setattr(mcp, "_vas_domain_policy_from_invoice_detail", lambda name, args: ("vas_estrategico", "bundle"))

    result = await mcp._validate_vas_subject(
        {
            "msisdn": "11999999999",
            "subject": "Aya Audiobooks Premium",
            "target_tool": "cancelar_vas_avulso",
        }
    )

    decision = result["transaction_decision"]
    assert decision["target_tool"] == "tratar_vas_estrategico"
    assert decision["resolved_arguments"]["subject"] == "Aya Audiobooks Premium"
    assert decision["resolved_arguments"]["_vas_subject_prevalidated"] is True
    assert decision["resolved_arguments"]["type"] == "bundle"
