"""Audit locally scored native tables against completion and read-input receipts."""
import hashlib
import importlib.util
import json
from pathlib import Path

B = Path(__file__).resolve().parent
E = B.parent
CV = E / "pangenome-reference-cv-20261014"
TRACK = E / "track-a-scoring-20261018"


def load(path):
    return json.loads(path.read_text())


def sha(path):
    return hashlib.sha256(path.read_bytes()).hexdigest()


def main():
    spec = importlib.util.spec_from_file_location("track", TRACK / "score_track_a.py")
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    result = load(TRACK / "TRACK_A_RESULT.json")
    pilot_plan = load(CV / "typing-pilot/PLAN.json")
    verified, failures = [], []
    pairs = {}
    for donor, arm in sorted({(r["donor"], r["arm"]) for r in result["rows"]}):
        table, aliases = module.arm_paths(donor, arm)
        receipt_path = table.parent / "COMPLETE.json"
        try:
            if receipt_path.exists():
                receipt = load(receipt_path)
                assert receipt["status"] == "complete"
                assert receipt["donor"] == donor and receipt["panel"] == arm
                assert receipt["native_table_sha256"] == sha(table)
                pair_sha = receipt["pairs_sha256"]
                source = str(receipt_path.relative_to(E))
                receipt_sha = sha(receipt_path)
            else:
                assert arm == "ipd" and donor in pilot_plan["original_controls"]
                historical = (CV / "pilot-comparison/partial-inputs/development-WGS-MHC-typing-v1"
                              / "t1k/runs" / donor / "COMPLETE.json")
                previous = load(historical)
                assert previous["status"] == "complete"
                assert previous["output_sha256"]["t1k_original/calls_genotype.tsv"] == sha(table)
                pair_sha = previous["pairs_sha256"]
                assert pair_sha == next(r["pairs_sha256"] for r in pilot_plan["donors"] if r["donor"] == donor)
                source = str(historical.relative_to(E))
                receipt_sha = sha(historical)
            if donor in pairs:
                assert pair_sha == pairs[donor], "Read-input receipt differs across arms"
            pairs[donor] = pair_sha
            if aliases:
                reference_receipt = load(aliases.parent / "COMPLETE.json")
                assert sha(aliases) == reference_receipt["output_sha256"]["aliases.json"]
            verified.append({"donor": donor, "arm": arm, "table_sha256": sha(table),
                             "pairs_sha256": pair_sha, "receipt": source,
                             "receipt_sha256": receipt_sha})
        except (AssertionError, KeyError, FileNotFoundError) as error:
            failures.append({"donor": donor, "arm": arm, "error": repr(error)})
    out = {"status": "verified" if not failures else "verification_failed",
           "verified_arm_tables": len(verified), "donors": len(pairs),
           "rows": verified, "failures": failures,
           "track_result_sha256": sha(TRACK / "TRACK_A_RESULT.json"),
           "script_sha256": sha(Path(__file__)),
           "limitations": [
               "Checks locally collected receipts, hashes and identical paired-read manifest per donor; no bulk read rehash.",
               "Two historical original-IPD pilot controls use their original completion receipts and frozen pilot read-input bindings.",
           ]}
    (B / "TRACK_INPUT_VERIFICATION.json").write_text(json.dumps(out, indent=2) + "\n")
    print(json.dumps({k: out[k] for k in ("status", "verified_arm_tables", "donors", "failures")}))
    if failures:
        raise SystemExit(1)


if __name__ == "__main__":
    main()
