"""Paired label-leakage control on a pinned public Nestor CSV. Python 3, offline."""
import argparse
import csv
import hashlib
import io
import json
import re
from pathlib import Path

parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("csv_file", type=Path)
parser.add_argument("report", type=Path, help="unused JSON filename")
args = parser.parse_args()
raw = args.csv_file.read_bytes()
digest = hashlib.sha256(raw).hexdigest()
if digest != "4fdc10728bb8d579ae310ee12bb613dc7068ded2050c301674e78bbfbbd189f0":
    parser.error("CSV differs from the pinned v0.4.6 file; compare download and revision")

other = {"PM01": "PM02", "PM02": "PM01"}
cohort = []
taken = dict.fromkeys(other, 0)
reader = csv.DictReader(io.StringIO(raw.decode("utf-8-sig"), newline=""), escapechar="\\")
for ordinal, row in enumerate(reader, start=1):
    label = row["PMType"]
    if label not in taken or taken[label] == 8 or not row["OriginalShorttext"].strip():
        continue
    cohort.append((ordinal, row))
    taken[label] += 1
    if all(count == 8 for count in taken.values()):
        break
if sum(taken.values()) != 16:
    parser.error("expected eight rows per label")

def text_rule(text):
    return "PM02" if re.search(r"\breplace\b", text, re.IGNORECASE) else "PM01"

def echo_label(row):
    return row["PMType"]

observations = []
for ordinal, row in cohort:
    reference = row["PMType"]
    flipped = {**row, "PMType": other[reference]}
    observations.append({
        "csvRecord": ordinal,
        "reference": reference,
        "textPrediction": text_rule(row["OriginalShorttext"]),
        "textAfterFlip": text_rule(flipped["OriginalShorttext"]),
        "echoPrediction": echo_label(row),
        "echoAfterFlip": echo_label(flipped),
    })
report = {"inputSha256": digest, "rowsPerLabel": taken, "observations": observations}
for mode in ("text", "echo"):
    report[mode] = {
        "correct": sum(r[mode + "Prediction"] == r["reference"] for r in observations),
        "changedOnFlip": sum(r[mode + "Prediction"] != r[mode + "AfterFlip"] for r in observations),
    }
with args.report.open("x", encoding="utf-8") as f:
    json.dump(report, f, ensure_ascii=False, indent=2)
    f.write("\n")
print(json.dumps({k: report[k] for k in ("rowsPerLabel", "text", "echo")}))
