from pathlib import Path

from contas_mcp.servers.contas_mcp_server.discount_history_service import DiscountHistoryMockService
from app.domain.contas import ContasDomainService
from app.domain.contas.workflow_actions import build_contas_workflow_actions


FIXTURE = Path(__file__).resolve().parents[2] / "app" / "domain" / "contas" / "fixtures" / "discount_history.json"


def test_discount_history_mock_returns_structured_authoritative_reason():
    service = DiscountHistoryMockService(FIXTURE)
    result = service.consultar_historico_descontos(msisdn="11999999999")
    assert result["success"] is True
    expired = next(row for row in result["discounts"] if row["discount_status"] == "EXPIRED")
    assert expired["plan_name"] == "TIM Black A 8.0"
    assert expired["previous_value"] == 80.0
    assert expired["current_value"] == 0.0
    assert expired["termination_reason"] == "FIM_PERIODO_FIDELIDADE"
    assert expired["termination_reason_description"] == "O período de fidelidade contratado foi encerrado."


def test_discount_history_mock_can_filter_plan_without_inventing_other_reason():
    service = DiscountHistoryMockService(FIXTURE)
    result = service.consultar_historico_descontos(msisdn="11999999999", nome_plano="CTRL")
    assert result["success"] is True
    assert len(result["discounts"]) == 1
    assert result["discounts"][0]["discount_status"] == "ACTIVE"
    assert result["discounts"][0]["termination_reason"] is None


def test_termino_desconto_formats_only_structured_discount_history_facts():
    service = DiscountHistoryMockService(FIXTURE)
    evidence = service.consultar_historico_descontos(msisdn="11999999999", nome_plano="TIM Black")
    action = build_contas_workflow_actions(ContasDomainService()).get("formatar_capability_resposta")
    result = action({"tipo": "termino_desconto", "discount_evidence": evidence}, {"input": {}})
    text = result["mensagem"]
    assert result["discount_reason_grounded"] is True
    assert result["epistemic_status"] == "grounded_fact"
    assert "TIM Black A 8.0" in text
    assert "R$ 80,00" in text
    assert "20/11/2025" in text
    assert "O período de fidelidade contratado foi encerrado." in text
    assert "FIM_PERIODO_FIDELIDADE" not in text


def test_termino_desconto_active_discount_without_reason_remains_non_conclusive():
    service = DiscountHistoryMockService(FIXTURE)
    evidence = service.consultar_historico_descontos(msisdn="11999999999", nome_plano="CTRL")
    action = build_contas_workflow_actions(ContasDomainService()).get("formatar_capability_resposta")
    result = action({"tipo": "termino_desconto", "discount_evidence": evidence}, {"input": {}})
    assert result["discount_reason_grounded"] is False
    assert result["epistemic_status"] == "insufficient_evidence"
    assert "não informam o motivo" in result["mensagem"]


def test_discount_history_temporal_reference_matches_last_invoice_fixture():
    import json

    service = DiscountHistoryMockService(FIXTURE)
    result = service.consultar_historico_descontos(msisdn="11999999999", nome_plano="TIM Black")
    expired = result["discounts"][0]

    invoice_fixture = FIXTURE.parent / "invoice_pdf_include_danfe_true.json"
    invoice = json.loads(invoice_fixture.read_text(encoding="utf-8"))
    summary = {row.get("desc"): row for row in invoice.get("Fatura Resumo", []) if isinstance(row, dict)}
    line = invoice["1199999999"]["Planos"]["TIM Black A 8.0"]
    billed_discount = next(row for row in line["descontos"] if row["desc"].startswith("Desc Fidel 80 TIM Black"))

    assert result["as_of_date"] == "2025-11-20"
    assert result["last_billed_period"] == summary["PERÍODO"]["period"] == "14/10 a 13/11"
    assert result["last_invoice_issue_date"] == "2025-11-20"
    assert summary["EMISSÃO"]["emissao"] == "20/11/2025"
    assert expired["current_value"] == 0.0
    assert expired["current_value_reference"] == "contract_as_of_date"
    assert expired["last_billed_discount_value"] == abs(float(billed_discount["value"])) == 80.0
    assert expired["last_billed_status"] == "APPLIED"


def test_termino_desconto_explains_contract_vs_last_billed_period_without_contradiction():
    service = DiscountHistoryMockService(FIXTURE)
    evidence = service.consultar_historico_descontos(msisdn="11999999999", nome_plano="TIM Black")
    action = build_contas_workflow_actions(ContasDomainService()).get("formatar_capability_resposta")
    result = action({"tipo": "termino_desconto", "discount_evidence": evidence}, {"input": {}})
    text = result["mensagem"]

    assert "O último período faturado com esse desconto foi 14/10 a 13/11" in text
    assert "com R$ 80,00 de desconto" in text
    assert "na fatura emitida em 20/11/2025" in text
    assert "a situação contratual em 20/11/2025 já consta como encerrada" in text
