#!/usr/bin/env python3
"""Compare a local NPI status export with the dated Kit Rx acceptance cases. No network access."""
import argparse
import csv
import sys
from collections import defaultdict
from pathlib import Path

HERE = Path(__file__).resolve().parent
STATES = {"active", "deactivated"}


def read_statuses(path):
    with path.open(encoding="utf-8-sig", newline="") as f:
        reader = csv.DictReader(f, strict=True)
        names = reader.fieldnames or []
        if len(names) != len(set(names)) or not {"npi", "registry_status"}.issubset(names):
            raise ValueError(f"{path.name} needs distinct column names including npi and registry_status.")
        for row in reader:
            if None in row or any(value is None for value in row.values()):
                raise ValueError(f"{path.name} has an incomplete or extra field on line {reader.line_num}.")
            yield row["npi"].strip(), row["registry_status"].strip().lower()


def compare(reference, observed):
    expected = {}
    for npi, status in read_statuses(reference):
        if len(npi) != 10 or not npi.isascii() or not npi.isdigit() or npi in expected or status not in STATES:
            raise ValueError("The reference contains an invalid or duplicate case.")
        expected[npi] = status
    if not expected:
        raise ValueError("The reference contains no cases.")

    results = defaultdict(list)
    for npi, status in read_statuses(observed):
        if npi in expected:
            results[npi].append(status)

    output = csv.writer(sys.stdout, lineterminator="\n")
    output.writerow(("npi", "expected_status", "observed_status", "result"))
    matches = 0
    for npi, target in expected.items():
        values = results.get(npi, [])
        observed_status = ""
        if not values:
            result = "missing"
        elif len(values) > 1:
            result = "duplicate"
        elif values[0] not in STATES:
            result = "unrecognized_status"
        else:
            observed_status = values[0]
            result = "match" if observed_status == target else "mismatch"
        matches += result == "match"
        output.writerow((npi, target, observed_status, result))
    print(f"{matches} of {len(expected)} reference cases matched.", file=sys.stderr)
    return 0 if matches == len(expected) else 1


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("export", type=Path, help="Local CSV with npi and registry_status columns")
    parser.add_argument("--reference", type=Path, default=HERE / "nppes-status-cases.csv")
    args = parser.parse_args()
    try:
        sys.exit(compare(args.reference, args.export))
    except (OSError, UnicodeError, ValueError, csv.Error) as exc:
        parser.exit(2, f"Could not compare files. {exc}\n")
