from __future__ import annotations

from types import SimpleNamespace

import pytest

from agent_framework.runtime.agent_runtime import AgentRuntimeMixin
from app.domain.contas.workflow_actions import build_contas_workflow_actions


class DummyAgent(AgentRuntimeMixin):
    pass


class Doc:
    def __init__(self, ident: str, score: float):
        self.id = ident
        self.score = score


class RagResult:
    def __init__(self, query: str):
        self.query = query
        self.latency_ms = 3
        self.documents = [Doc("d1", 0.9)]
        self.graph_neighbors = []
        self.metadata = {"rewritten": False}

    def as_prompt_context(self):
        return "ORIENTACAO OFICIAL DO PARCEIRO"


class RagService:
    def __init__(self):
        self.calls = []

    async def retrieve(self, query, *, namespace, graph_node, rewrite):
        self.calls.append((query, namespace, graph_node, rewrite))
        return RagResult(query)


@pytest.mark.asyncio
async def test_tool_pode_forcar_rag_e_fornecer_query_override():
    rag = RagService()
    agent = DummyAgent()
    agent.rag_service = rag
    agent.guardrail_pipeline = None
    agent.settings = SimpleNamespace(
        SKIP_RAG_WHEN_MCP_SUFFICIENT=True,
        ENABLE_RAG_QUERY_REWRITE=False,
        ENABLE_RAG_CONTEXT_COMPRESSION=False,
    )
    state = {
        "sanitized_input": "quero cancelar o paramount",
        "user_text": "quero cancelar o paramount",
        "route": "vas_agent",
        "mcp_results": [{
            "ok": True,
            "result": {
                "status": "COMPLETED",
                "output": {
                    "registrar_nao": {
                        "requires_rag": True,
                        "rag_queries": [
                            "Como cancelar Paramount+ no parceiro?",
                            "Procedimento oficial Paramount+",
                        ],
                    }
                },
            },
        }],
    }
    context, metadata = await agent._retrieve_rag_context(state)
    assert context == "ORIENTACAO OFICIAL DO PARCEIRO"
    assert rag.calls[0][0] == "Como cancelar Paramount+ no parceiro?\nProcedimento oficial Paramount+"
    assert metadata["required_by_tool"] is True
    assert metadata["query_overridden_by_tool"] is True
    assert agent.build_direct_mcp_answer(state, state["mcp_results"], agent_label="VAS") is None


def test_vas_estrategico_rejeitado_declara_rag_sem_executar_rag_no_dominio():
    class Service:
        class Client:
            def abrir_protocolo(self, payload):
                return {"interactionProtocol": "P1"}
        client = Client()

    action = build_contas_workflow_actions(Service()).get("registrar_atendimento_vas_estrategico")
    result = action({
        "linhas": [{
            "msisdn": "11999999999",
            "bundle_names": [],
            "estrategico_names": ["Paramount+ Mensal", "YouTube Premium"],
        }],
        "mensagem_base": "orientação genérica",
    }, {
        "input": {"resposta_usuario": "NAO"},
        "execution_id": "wf1",
        "vars": {},
    })
    assert result["requires_rag"] is True
    assert result["rag_queries"] == [
        "Como cancelar o serviço Paramount+ Mensal no parceiro? Procedimento oficial de cancelamento.",
        "Como cancelar o serviço YouTube Premium no parceiro? Procedimento oficial de cancelamento.",
    ]
