from app.domain.contas.workflow_actions import build_contas_workflow_actions
from app.domain.contas.conversation_policy import evaluate
from app.extensions.tim_judges import TimResponseQualityJudge


class _Service:
    def invoice_explanation(self, *, msisdn, **params):
        return {
            "billing_analysis": {
                "invoiceExplanation": "Resumo global com Tamboro e Fashion.",
                "currentInvoice": [{
                    "type": "servicos_contratados_de_parceiros",
                    "items": [
                        {"desc": "VOD + Canais abertos", "value": "10.0", "date": "2025-11-01T00:00:00.000Z"},
                        {"desc": "VOD + Canais abertos", "value": "10.0", "date": "2025-11-03T00:00:00.000Z"},
                        {"desc": "Tamboro Mensal", "value": "14.99", "date": "2025-11-01T00:00:00.000Z"},
                    ],
                }],
            }
        }


def test_invoice_explanation_focuses_named_vod_charges_instead_of_global_summary():
    action = build_contas_workflow_actions(_Service()).get("preparar_invoice_explanation")
    out = action({}, {"input": {"msisdn": "119", "message": "tem duas cobranças de VOD mais Canais abertos aqui que eu não reconheço"}})
    text = out["explicacao_base"]
    assert "2 cobranças de VOD + Canais abertos" in text
    assert "R$ 10,00 em 01/11/2025" in text
    assert "R$ 10,00 em 03/11/2025" in text
    assert "Tamboro" not in text


def test_invoice_explanation_without_specific_focus_keeps_global_summary():
    action = build_contas_workflow_actions(_Service()).get("preparar_invoice_explanation")
    out = action({}, {"input": {"msisdn": "119", "message": "me explica essa fatura"}})
    assert out["explicacao_base"] == "Resumo global com Tamboro e Fashion."


def test_post_terminal_no_match_becomes_fresh_interaction_not_old_workflow_resume():
    decision = evaluate({
        "user_text": "ah espera",
        "intent": "contas_no_match",
        "route_decision": {"intent": "contas_no_match", "method": "llm"},
        "operational_context_reset": True,
        "history": [],
    })
    assert decision is not None
    assert decision.intent == "contas_post_terminal_reentry"
    assert "Em que posso ajudar" in decision.answer


class _LLM:
    async def ainvoke(self, *args, **kwargs):
        return '{"allowed": true, "label": "BAIXA_QUALIDADE", "score": 1, "reason": "ruim"}'


async def test_tim_response_quality_score_one_means_one_tenth():
    judge = TimResponseQualityJudge(llm=_LLM(), threshold=0.7)
    result = await judge.evaluate("pergunta", "resposta", {})
    assert result.score == 0.1
    assert result.passed is False
