"""Audit the two synthetic six-row Week 6 handoffs without importing a record."""
import argparse
from collections import Counter
import json
from pathlib import Path

OUTCOMES = ("accepted", "duplicate", "quarantined", "conflict")
# Row order I-01 to I-06 in the published manual ledger.
EXPECTED = {
    "first": ("accepted", "duplicate", "quarantined", "quarantined", "conflict", "accepted"),
    "replay": ("duplicate", "duplicate", "quarantined", "quarantined", "conflict", "duplicate"),
}


def audit(report):
    batch, items, counts = report["batch"], report["items"], report["counts"]
    ids = [row["id"] for row in items]
    expected = dict(zip(("I-%02d" % i for i in range(1, 7)), EXPECTED[batch]))
    if sorted(ids) != sorted(expected) or any(row["outcome"] not in OUTCOMES for row in items):
        raise ValueError(f"{batch}: need six distinct case IDs and known outcomes")
    if set(counts) - set(OUTCOMES) or any(type(v) is not int or v < 0 for v in counts.values()):
        raise ValueError(f"{batch}: invalid outcome count")
    if type(report["input"]) is not int or report["input"] != len(items):
        raise ValueError(f"{batch}: input count differs from the six rows")
    rows = Counter(row["outcome"] for row in items)
    count_errors = {k: {"reported": counts.get(k), "from_rows": rows[k]}
                    for k in OUTCOMES if counts.get(k) != rows[k]}
    row_errors = [{"id": row["id"], "reported": row["outcome"], "expected": expected[row["id"]]}
                  for row in items if row["outcome"] != expected[row["id"]]]
    return {"batch": batch, "input": len(items), "reported_total": sum(counts.values()),
            "count_errors": count_errors, "row_errors": row_errors,
            "matches_fixture": not count_errors and not row_errors}


parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("source", type=Path)
parser.add_argument("output", type=Path)
args = parser.parse_args()
try:
    reports = json.loads(args.source.read_text(encoding="utf-8"))
    if sorted(r["batch"] for r in reports) != sorted(EXPECTED):
        raise ValueError("need one first batch and one replay")
    result = [audit(report) for report in reports]
    with args.output.open("x", encoding="utf-8") as dest:
        json.dump(result, dest, indent=2)
        dest.write("\n")
    print(" / ".join("%s: %s" % (r["batch"], "PASS" if r["matches_fixture"] else "REVIEW")
                     for r in result))
    raise SystemExit(0 if all(r["matches_fixture"] for r in result) else 1)
except (OSError, ValueError, KeyError, TypeError) as error:
    parser.exit(2, f"{error}\n")
