"""Pipeline A: denied/partial visits become frequency-7 replacement claims."""
from datetime import date
from decimal import Decimal
from cyclone.rebill.pipeline_a import build_pipeline_a_claims
from cyclone.rebill.reconcile import VisitRow, ReconcileOutcome, OutcomeCategory
from cyclone.rebill.carc_filter import CarcDecision


def _outcome(date_, member, proc, billed, cat, unpaid=Decimal("0")):
    visit = VisitRow(date=date_, member_id=member, procedure=proc, billed=Decimal(billed))
    return ReconcileOutcome(visit, cat, unpaid, 0)


def test_pipeline_a_emits_frequency_7():
    """CLM05-3 must be 7 (replacement), preserving the original claim_submit_id."""
    out = build_pipeline_a_claims(
        original_claim_id="ORIG-001",
        visit_outcomes=[
            _outcome(date(2026, 6, 27), "J813715", "T1019", "2.32",
                     OutcomeCategory.DENIED, unpaid=Decimal("2.32")),
        ],
        carc_decisions=[CarcDecision.REBILL],
        cas_reasons_per_visit=[()],
    )
    assert len(out) == 1
    assert out[0].claim_id == "ORIG-001"
    assert out[0].frequency_code == "7"
    assert out[0].svc_date == date(2026, 6, 27)


def test_pipeline_a_excludes_carc_excluded_visits():
    out = build_pipeline_a_claims(
        original_claim_id="ORIG-002",
        visit_outcomes=[
            _outcome(date(2026, 6, 27), "J813715", "T1019", "2.32",
                     OutcomeCategory.DENIED),
        ],
        carc_decisions=[CarcDecision.EXCLUDED],
        cas_reasons_per_visit=[("CO-45",)],
    )
    assert out == []  # not emitted


def test_pipeline_a_surfaces_review_visits_with_flag():
    out = build_pipeline_a_claims(
        original_claim_id="ORIG-003",
        visit_outcomes=[
            _outcome(date(2026, 6, 27), "J813715", "T1019", "2.32",
                     OutcomeCategory.DENIED),
        ],
        carc_decisions=[CarcDecision.REVIEW],
        cas_reasons_per_visit=[("PI-16",)],
    )
    assert len(out) == 1
    assert out[0].needs_review is True
