"""Summary CSV for SP41.

One row per visit, classified into one of:
  REBILLED_A          — pipeline A emitted a frequency-7 replacement
  REBILLED_B          — pipeline B emitted a fresh 837P
  EXCLUDED_CARC       — CO-45/CO-26/CO-129 (or other excluded CARC)
  EXCLUDED_PAYER      — non-CO_TXIX payer per AxisCare API spot audit
  EXCLUDED_NO_EVV     — no Authorized=Yes AND no AxisCare EVV ref
  EXCLUDED_TIMELY_FILING — DOS > 120 days before run date, no override
"""
import csv
from dataclasses import dataclass
from decimal import Decimal
from pathlib import Path

from cyclone.rebill.reconcile import VisitRow

REBILLED_A = "REBILLED_A"
REBILLED_B = "REBILLED_B"
EXCLUDED_CARC = "EXCLUDED_CARC"
EXCLUDED_PAYER = "EXCLUDED_PAYER"
EXCLUDED_NO_EVV = "EXCLUDED_NO_EVV"
EXCLUDED_TIMELY_FILING = "EXCLUDED_TIMELY_FILING"


@dataclass(frozen=True)
class SummaryRow:
    """One visit + its post-pipeline disposition for the operator audit trail."""

    visit: VisitRow
    disposition: str
    unpaid: Decimal
    cas_reasons: tuple[str, ...]
    file_path: str  # relative to dev/rebills/<date>/


def write_summary_csv(rows: list[SummaryRow], out_path: Path) -> int:
    """Write the summary CSV; return the number of rows written."""
    out_path.parent.mkdir(parents=True, exist_ok=True)
    with out_path.open("w", newline="") as f:
        w = csv.writer(f)
        w.writerow([
            "dos", "member_id", "procedure", "billed",
            "disposition", "unpaid", "cas_reasons", "file_path",
        ])
        for r in rows:
            w.writerow([
                r.visit.date.isoformat(),
                r.visit.member_id,
                r.visit.procedure,
                str(r.visit.billed),
                r.disposition,
                str(r.unpaid),
                "|".join(r.cas_reasons),  # pipe-separated; no collision with J-prefixed member IDs or relative file paths
                r.file_path,
            ])
    return len(rows)
