"""Integration test: load the realistic CO Medicaid 835 fixture and validate it end-to-end."""
from decimal import Decimal
from pathlib import Path

from cyclone.parsers.parse_835 import parse
from cyclone.parsers.payer import PayerConfig835
from cyclone.parsers.validator_835 import validate

FIXTURE = Path(__file__).parent / "fixtures" / "co_medicaid_835.txt"


def test_co_fixture_two_claims_pass():
    result = parse(FIXTURE.read_text(), PayerConfig835.co_medicaid_835())
    cfg = PayerConfig835.co_medicaid_835()
    report = validate(result, cfg)
    assert result.summary.total_claims == 2
    assert report.passed is True
    assert report.errors == []


def test_first_claim_has_two_service_lines():
    result = parse(FIXTURE.read_text(), PayerConfig835.co_medicaid_835())
    c1 = result.claims[0]
    assert c1.payer_claim_control_number == "t991102986o1c1d"
    assert len(c1.service_payments) == 2
    assert c1.service_payments[0].procedure_code == "T1019"
    assert c1.service_payments[0].modifiers == ["U2"]
    assert c1.service_payments[1].service_date is not None


def test_second_claim_has_four_service_lines():
    result = parse(FIXTURE.read_text(), PayerConfig835.co_medicaid_835())
    c2 = result.claims[1]
    assert c2.payer_claim_control_number == "t991102986o1c2d"
    assert len(c2.service_payments) == 4
    assert c2.per_diem_covered_days == Decimal("4")


def test_payer_and_payee_match_co_config():
    result = parse(FIXTURE.read_text(), PayerConfig835.co_medicaid_835())
    assert result.payer.name == "CO_TXIX"
    assert result.payer.id == "7912900843"
    assert result.financial_info.payer_tax_id in {"81-1725341", "84-0644739"}
    assert result.payee.npi == "1881068062"
    assert result.payee.name == "TOC, Inc."


def test_bpr_vs_clp_balance_holds():
    """BPR02 (241.16) = CLP04 sum (85.40 + 155.76)."""
    result = parse(FIXTURE.read_text(), PayerConfig835.co_medicaid_835())
    clp_sum = sum((c.total_paid for c in result.claims), start=Decimal("0"))
    assert result.financial_info.paid_amount == clp_sum
    assert result.financial_info.paid_amount == Decimal("241.16")


def test_per_claim_clp_vs_svc_balance_holds():
    result = parse(FIXTURE.read_text(), PayerConfig835.co_medicaid_835())
    for c in result.claims:
        svc_sum = sum((sp.payment for sp in c.service_payments), start=Decimal("0"))
        assert c.total_paid == svc_sum, f"claim {c.payer_claim_control_number}: CLP04={c.total_paid} != sum(SVC03)={svc_sum}"
