"""835 SVC-level parser with member_id at SVC scope."""
from pathlib import Path
from collections import defaultdict
from decimal import Decimal
from cyclone.rebill.parse_835_svc import parse_835_svc

FIX = Path(__file__).parent / "fixtures" / "835_sample_svc_with_member.txt"

def test_parse_835_svc_extracts_member_id():
    """NM1*QC NM109 at the CLP scope must propagate to that CLP's SVC rows;
    the multi-claim fixture confirms each CLP's NM1*QC lands on its own SVCs."""
    rows = list(parse_835_svc(FIX))
    assert len(rows) >= 1
    by_claim: dict[str, list[str]] = defaultdict(list)
    for r in rows:
        by_claim[r.claim_id].append(r.member_id)
        assert r.procedure  # non-empty
        assert r.svc_date   # non-empty
        assert r.charge > 0
    # First CLP (T1001) -> original fixture member
    assert all(mid == "J813715" for mid in by_claim["T1001"]), by_claim
    # Second CLP (T1002, status 4) -> its own NM1*QC
    assert all(mid == "OTHER-MEMBER-A" for mid in by_claim["T1002"]), by_claim
    # Third CLP (T1003, status 22) -> its own NM1*QC
    assert all(mid == "OTHER-MEMBER-B" for mid in by_claim["T1003"]), by_claim

def test_parse_835_svc_extracts_cas_reasons():
    """CAS segments after DTM*472 must be captured (post-DTM*472 ordering)."""
    rows = list(parse_835_svc(FIX))
    # at least one row should have an OA-18 reason
    assert any("OA-18" in r.cas_reasons for r in rows)

def test_parse_835_svc_picks_up_status_22_reversals():
    """Status 22 (reversal of previous payment) must be preserved, along with
    status 1 (primary) and status 4 (denied)."""
    rows = list(parse_835_svc(FIX))
    statuses = {r.status for r in rows}
    assert statuses == {"1", "4", "22"}
