"""Reproduce the 2025 out-of-network issuer sensitivity table from the CMS PY2027 PUF.

Install openpyxl and unzip https://download.cms.gov/marketplace-puf/2027/transparency-in-coverage-puf.zip.
Run in the directory where you want the CSV:
    python3 marketplace_issuer_sensitivity.py transparency-in-coverage-puf.xlsx
Use --csv PATH to choose the output filename and --json PATH for an additional JSON export.
The published analysis used an XLSX with SHA-256
26a06a26c62d0d5754ab5eb0f15bff9f0ed907c18de38a6f0f8c718f6cbeac30.
"""
import argparse
import csv
import json
from collections import defaultdict
from fractions import Fraction
from pathlib import Path

from openpyxl import load_workbook


FIELD_PAIRS = [
    (f"Plan_Number_Claims_Received_{network}_{service}", f"Plan_Number_Claims_Denied_{network}_{service}")
    for network in ("In_Network", "Out_Of_Network")
    for service in ("Behavioral_Health_Only", "Non_Behavioral_Health")
]


def matched_plans(records):
    groups = defaultdict(lambda: defaultdict(list))
    seen = set()
    for record in records:
        plan = record["Plan_ID"]
        if not plan or record["QHP or SADP?"] != "QHP":
            continue
        if plan in seen:
            raise ValueError(f"Duplicate individual medical plan ID: {plan}")
        seen.add(plan)
        counts = [(record[received], record[denied]) for received, denied in FIELD_PAIRS]
        if all(type(r) is int and type(d) is int and r > 0 and 0 <= d <= r for r, d in counts):
            state = record["State"]
            issuer = str(record["Issuer_ID"]).zfill(5)
            if not state or not (len(issuer) == 5 and issuer.isdigit()):
                raise ValueError(f"Missing state or invalid HIOS issuer for plan {plan}")
            groups[state][issuer].append(counts)
    return groups


def summarize(issuers):
    plans = [plan for rows in issuers.values() for plan in rows]
    # Keep the four denominators because the study's two volume screens use all four.
    received = [sum(plan[group][0] for plan in plans) for group in range(4)]
    bh_denied = sum(plan[2][1] for plan in plans)
    other_denied = sum(plan[3][1] for plan in plans)
    bh_rate = Fraction(100 * bh_denied, received[2]) if plans else None
    other_rate = Fraction(100 * other_denied, received[3]) if plans else None
    return {
        "plans": len(plans), "issuers": len(issuers),
        "minimumReceivedAcrossFourGroups": min(received),
        "behavioralHealthReceived": received[2], "behavioralHealthDenied": bh_denied,
        "otherReceived": received[3], "otherDenied": other_denied,
        "behavioralHealthDenialPct": bh_rate, "otherDenialPct": other_rate,
        "gapPp": bh_rate - other_rate if plans else None,
    }


def state_comparisons(groups):
    rows = []
    for state, issuers in sorted(groups.items()):
        volumes = {issuer: sum(plan[2][0] for plan in plans) for issuer, plans in issuers.items()}
        # Use the lowest five-digit HIOS ID to break a tie in claims received.
        removed = min(volumes, key=lambda issuer: (-volumes[issuer], issuer))
        baseline = summarize(issuers)
        remaining = summarize({issuer: plans for issuer, plans in issuers.items() if issuer != removed})
        change = remaining["gapPp"] - baseline["gapPp"] if remaining["plans"] else None
        rows.append({
            "state": state, "excludedIssuerId": removed,
            "excludedBehavioralHealthSharePct": round(100 * volumes[removed] / baseline["behavioralHealthReceived"], 6),
            "baseline": export_metrics(baseline), "remaining": export_metrics(remaining),
            "gapChangePp": round(float(change), 6) if change is not None else None,
        })
    return rows


def export_metrics(metrics):
    return {key: round(float(value), 6) if isinstance(value, Fraction) else value for key, value in metrics.items()}


def csv_row(row):
    columns = {
        "state": row["state"],
        "excluded_hios_issuer_id": row["excludedIssuerId"],
        "excluded_share_of_out_of_network_behavioral_health_received_pct": row["excludedBehavioralHealthSharePct"],
    }
    fields = {
        "plans": "matched_plans", "issuers": "issuers",
        "minimumReceivedAcrossFourGroups": "minimum_received_across_four_groups",
        "behavioralHealthReceived": "out_of_network_behavioral_health_received",
        "behavioralHealthDenied": "out_of_network_behavioral_health_denied",
        "otherReceived": "out_of_network_other_received", "otherDenied": "out_of_network_other_denied",
        "behavioralHealthDenialPct": "out_of_network_behavioral_health_denial_pct",
        "otherDenialPct": "out_of_network_other_denial_pct", "gapPp": "out_of_network_gap_pp",
    }
    for cohort in ("baseline", "remaining"):
        metrics = row[cohort]
        for key, name in fields.items():
            columns[f"{cohort}_{name}"] = metrics[key]
        for threshold in (1000, 10000):
            columns[f"{cohort}_meets_{threshold}_claims_per_group"] = int(metrics["minimumReceivedAcrossFourGroups"] >= threshold)
    columns["gap_change_pp_remaining_minus_baseline"] = row["gapChangePp"]
    return columns


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("workbook", type=Path)
    parser.add_argument("--csv", type=Path, default=Path("cms-2025-marketplace-issuer-sensitivity.csv"),
                        help="destination for the state comparison CSV (defaults to the current directory)")
    parser.add_argument("--json", type=Path, help="optional destination for the nested JSON records")
    args = parser.parse_args()
    files = [p.resolve() for p in (args.workbook, args.csv, args.json) if p is not None]
    if len(files) != len(set(files)):
        parser.error("The workbook and output paths must be distinct.")
    workbook = load_workbook(args.workbook, read_only=True, data_only=True)
    try:
        sheet = workbook["Transparency 2027 - Ind QHP"]
        records = sheet.iter_rows(min_row=3, values_only=True)
        headers = next(records)
        groups = matched_plans(dict(zip(headers, row)) for row in records)
    finally:
        workbook.close()
    rows = state_comparisons(groups)
    if not rows:
        raise ValueError("No states have complete plan data in all four comparison groups")
    csv_rows = [csv_row(row) for row in rows]
    with args.csv.open("w", encoding="utf-8", newline="") as csv_file:
        writer = csv.DictWriter(csv_file, fieldnames=csv_rows[0], lineterminator="\n")
        writer.writeheader()
        writer.writerows(csv_rows)
    if args.json is not None:
        args.json.write_text(json.dumps(rows, indent=2, allow_nan=False) + "\n", encoding="utf-8")


if __name__ == "__main__":
    main()
