"""Independent verification of the PTP1B structural comparison.

Deliberately independent of analysis/ptp1b_common.py:
  * input   : legacy PDB-format files (primary pipeline used mmCIF)
  * parser  : fixed-column reader written here (primary used Bio.PDB.MMCIF2Dict)
  * fit     : Horn quaternion eigen-decomposition, cross-checked with
              Bio.PDB.Superimposer (primary used a NumPy SVD/Kabsch fit)
  * contacts: brute-force distance matrices (primary used a k-d tree)
  * SASA    : Bio.PDB.SASA.ShrakeRupley (primary used its own implementation)

Run:  python verification_tests.py            (writes verification_results.json)
      python verification_tests.py --rerun    (also re-executes the analysis scripts
                                               and checks the tables are reproduced)
"""
import sys, json, hashlib, subprocess, platform, copy
from pathlib import Path
from datetime import datetime, timezone
import numpy as np
import pandas as pd

ROOT = Path(__file__).resolve().parent
RAW, RES, FIG = ROOT / "data" / "raw", ROOT / "results", ROOT / "figures"
IDS = ("5K9W", "5K9V", "1T49")
PAIRS = (("5K9V", "5K9W"), ("1T49", "5K9W"), ("1T49", "5K9V"))
THREE = {"ALA": "A", "ARG": "R", "ASN": "N", "ASP": "D", "CYS": "C", "GLN": "Q", "GLU": "E", "GLY": "G", "HIS": "H", "ILE": "I", "LEU": "L",
         "LYS": "K", "MET": "M", "PHE": "F", "PRO": "P", "SER": "S", "THR": "T", "TRP": "W", "TYR": "Y", "VAL": "V"}
TESTS = []


def record(tid, requirement, description, passed, classification, evidence, method=""):
    TESTS.append(dict(id=tid, requirement=requirement, description=description, method=method,
                      status="pass" if passed else "FAIL", classification=classification, evidence=evidence))
    print(f"[{'pass' if passed else 'FAIL'}] {tid}: {description}")


# ----------------------------------------------------------------------------- parsing
def read_pdb(pid):
    atoms, seqres, header = [], [], ""
    for line in (RAW / f"{pid}.pdb").read_text().splitlines():
        rec = line[:6]
        if rec == "HEADER":
            header = line[62:66]
        elif rec == "SEQRES" and line[11] == "A":
            seqres += line[19:].split()
        elif rec in ("ATOM  ", "HETATM"):
            atoms.append(dict(group=rec.strip(), name=line[12:16].strip(), alt=line[16].strip(), resname=line[17:20].strip(), chain=line[21],
                              resnum=int(line[22:26]), icode=line[26].strip(), x=float(line[30:38]), y=float(line[38:46]), z=float(line[46:54]),
                              occ=float(line[54:60]), b=float(line[60:66]), element=line[76:78].strip().upper()))
        elif rec == "ENDMDL":
            break
    return header, seqres, pd.DataFrame(atoms)


def one_conformer(a):
    """Highest-occupancy conformer per atom name within a residue (ties: first in file)."""
    a = a.reset_index(drop=True)
    a["order"] = a.index
    a = a.sort_values(["occ", "order"], ascending=[False, True]).drop_duplicates(["group", "chain", "resnum", "resname", "name"]).sort_values("order")
    return a.drop(columns="order").reset_index(drop=True)


def horn(mobile, ref):
    """Horn (1987) closed-form absolute orientation with unit quaternions."""
    mc, rc = mobile.mean(0), ref.mean(0)
    A, B = mobile - mc, ref - rc
    S = A.T @ B
    Sxx, Sxy, Sxz, Syx, Syy, Syz, Szx, Szy, Szz = S.ravel()
    N = np.array([[Sxx + Syy + Szz, Syz - Szy, Szx - Sxz, Sxy - Syx],
                  [Syz - Szy, Sxx - Syy - Szz, Sxy + Syx, Szx + Sxz],
                  [Szx - Sxz, Sxy + Syx, -Sxx + Syy - Szz, Syz + Szy],
                  [Sxy - Syx, Szx + Sxz, Syz + Szy, -Sxx - Syy + Szz]])
    w, v = np.linalg.eigh(N)
    q0, qx, qy, qz = v[:, -1]
    R = np.array([[q0 * q0 + qx * qx - qy * qy - qz * qz, 2 * (qx * qy - q0 * qz), 2 * (qx * qz + q0 * qy)],
                  [2 * (qy * qx + q0 * qz), q0 * q0 - qx * qx + qy * qy - qz * qz, 2 * (qy * qz - q0 * qx)],
                  [2 * (qz * qx - q0 * qy), 2 * (qz * qy + q0 * qx), q0 * q0 - qx * qx - qy * qy + qz * qz]])
    return R, rc - R @ mc


def main(rerun=False):
    retr = {r["file"]: r for r in json.loads((ROOT / "provenance" / "retrieval.json").read_text())}

    # ---- 1. identifiers and checksums --------------------------------------------------
    ev, ok = {}, True
    for pid in IDS:
        for fmt in ("cif", "pdb"):
            fn = f"{pid}.{fmt}"
            data = (RAW / fn).read_bytes()
            sha = hashlib.sha256(data).hexdigest()
            ident = data[:100].decode("latin-1")
            id_ok = (f"data_{pid}" in ident) if fmt == "cif" else (data[62:66].decode() == pid)
            good = sha == retr[fn]["sha256"] and len(data) == retr[fn]["bytes"] and id_ok and retr[fn]["url"].endswith(fn)
            ok &= good
            ev[fn] = dict(sha256=sha, recorded_sha256=retr[fn]["sha256"], bytes=len(data), identifier_in_file_matches=id_ok, match=good)
    record("V1_checksums", 1, "All six coordinate files match their recorded SHA-256, size and PDB identifier", ok, "Independently verified", ev,
           "hashlib.sha256 on raw bytes vs provenance/retrieval.json; HEADER idCode / data_ block name")

    # ---- 2. residue and atom mapping ----------------------------------------------------
    S = {}
    ev, ok = {}, True
    for pid in IDS:
        header, seqres, atoms = read_pdb(pid)
        prot = one_conformer(atoms[(atoms.group == "ATOM") & (atoms.chain == "A")])
        S[pid] = dict(atoms=one_conformer(atoms[atoms.chain == "A"]), prot=prot, raw=atoms)
        obs = prot.drop_duplicates("resnum").set_index("resnum")["resname"]
        seq = [THREE[x] for x in seqres]
        best = max(range(-10, 11), key=lambda k: sum(0 <= r + k < len(seq) and seq[r + k] == THREE[n] for r, n in obs.items()))
        nmatch = sum(0 <= r + best < len(seq) and seq[r + best] == THREE[n] for r, n in obs.items())
        ca = prot[prot.name == "CA"].set_index("resnum")[["x", "y", "z"]]
        steps = np.linalg.norm(ca.loc[3:280].values - ca.loc[2:279].values, axis=1)
        motif = "".join(THREE[obs[r]] for r in range(214, 224))
        wpd = "".join(THREE[obs[r]] for r in (179, 180, 181))
        good = (nmatch == len(obs) and not prot.icode.any() and steps.min() > 3.6 and steps.max() < 4.0 and motif == "HCSAGIGRSG" and wpd == "WPD"
                and obs[215] == "CYS" and obs[221] == "ARG" and obs[182] == "PHE" and len(ca.loc[2:280]) == 279)
        ok &= good
        ev[pid] = dict(n_observed_residues=int(len(obs)), seqres_length=len(seq), seqres_index_offset=int(best), residues_matching_seqres=int(nmatch),
                       insertion_codes=bool(prot.icode.any()), consecutive_CA_distance_2_280_min_max_A=[float(steps.min()), float(steps.max())],
                       signature_motif_214_223=motif, residues_179_181=wpd, n_CA_2_280=int(len(ca.loc[2:280])))
    names = pd.DataFrame({p: S[p]["prot"].drop_duplicates("resnum").set_index("resnum")["resname"] for p in IDS}).loc[2:280]
    same = bool((names.nunique(axis=1) == 1).all())
    mp = pd.read_csv(ROOT / "structure_mapping.csv").set_index("native_resnum")
    map_agree = all((mp.loc[2:280, f"{p}_resname"].values == names[p].values).all() for p in IDS)
    ev["cross_structure"] = dict(identical_residue_names_2_280=same, legacy_PDB_names_equal_structure_mapping_csv=bool(map_agree),
                                 n_core_fit=int(mp["in_core_fit_set"].sum()), n_loop=int(mp["in_loop_window_176_187"].sum()))
    record("V2_mapping", 2, "Residue numbering maps 1:1 onto the construct sequence, the PTP signature motif sits at 214-223 (Cys215), WPD at 179-181, "
           "and residues 2-280 are identical and contiguous in all three entries", ok and same and map_agree, "Independently verified", ev,
           "legacy-PDB SEQRES vs ATOM records; consecutive CA-CA distances; comparison with structure_mapping.csv")

    # ---- 3. independent RMSD -------------------------------------------------------------
    prim = pd.read_csv(RES / "structural_comparison.csv")
    core = [r for r in range(2, 281) if not 176 <= r <= 187]
    allr, loop = list(range(2, 281)), list(range(176, 188))
    ev, ok, worst = {}, True, 0.0
    from Bio.PDB import PDBParser, Superimposer
    bio = {p: PDBParser(QUIET=True).get_structure(p, str(RAW / f"{p}.pdb"))[0]["A"] for p in IDS}
    for mob, ref in PAIRS:
        cm = S[mob]["prot"][S[mob]["prot"].name == "CA"].set_index("resnum")[["x", "y", "z"]]
        cr = S[ref]["prot"][S[ref]["prot"].name == "CA"].set_index("resnum")[["x", "y", "z"]]
        for fitname, fitset in (("core_2-280_excl_176-187", core), ("loop_included_2-280", allr)):
            R, t = horn(cm.loc[fitset].values, cr.loc[fitset].values)
            X = pd.DataFrame(cm.loc[allr].values @ R.T + t, index=allr)
            d = np.linalg.norm(X.values - cr.loc[allr].values, axis=1)
            dd = pd.Series(d, index=allr)
            mine = dict(fit_rmsd_A=float(np.sqrt((dd.loc[fitset] ** 2).mean())), rmsd_all_CA_2_280_A=float(np.sqrt((dd ** 2).mean())),
                        loop_176_187_rmsd_fitted_frame_A=float(np.sqrt((dd.loc[loop] ** 2).mean())), asp181_CA_displacement_A=float(dd.loc[181]))
            sup = Superimposer()
            sup.set_atoms([bio[ref][r]["CA"] for r in fitset], [bio[mob][r]["CA"] for r in fitset])
            mine_bio = float(sup.rms)
            row = prim[(prim.mobile == mob) & (prim.reference == ref) & (prim.fit_definition == fitname)].iloc[0]
            diffs = {k: abs(v - float(row[k])) for k, v in mine.items()}
            diffs["biopython_superimposer_fit_rmsd"] = abs(mine_bio - float(row["fit_rmsd_A"]))
            worst = max(worst, max(diffs.values()))
            ev[f"{mob}->{ref}|{fitname}"] = dict(independent=mine, biopython_fit_rmsd_A=mine_bio, primary={k: float(row[k]) for k in mine},
                                                 max_abs_difference_A=max(diffs.values()))
            ok &= max(diffs.values()) < 1e-3
    record("V3_rmsd", 3, f"Main RMSD and displacement values recomputed from legacy PDB files with a quaternion fit agree with the primary table "
           f"(largest absolute difference {worst:.2e} A; tolerance 1e-3 A)", ok, "Independently reproduced", ev,
           "fixed-column PDB parser + Horn quaternion superposition; Bio.PDB.Superimposer as a third implementation")

    # ---- 4. pocket assignment --------------------------------------------------------------
    a = S["1T49"]["atoms"]
    lig = a[(a.group == "HETATM") & (a.resname == "892")]
    prot = S["1T49"]["prot"]
    D = np.linalg.norm(prot[["x", "y", "z"]].values[:, None] - lig[["x", "y", "z"]].values[None], axis=-1)
    dmin = pd.Series(D.min(1)).groupby(prot.resnum.values).min()
    nb = pd.read_csv(RES / "ligand892_neighbourhood.csv")
    sets_ok, sets = True, {}
    for c in (3.5, 4.0, 4.5, 5.0):
        mine = sorted(int(r) for r in dmin[dmin <= c].index)
        theirs = sorted(int(r) for r in nb[nb[f"within_{c}A"]].resnum)
        sets[f"{c}A"] = dict(independent=mine, primary=theirs, equal=mine == theirs)
        sets_ok &= mine == theirs
    sg = S["1T49"]["raw"]
    sg = sg[(sg.chain == "A") & (sg.resnum == 215) & (sg.name == "SG")]
    sgd = {f"altloc {r.alt or '-'}": float(np.linalg.norm(lig[["x", "y", "z"]].values - np.array([r.x, r.y, r.z]), axis=1).min()) for r in sg.itertuples()}
    pj = json.loads((RES / "pocket_analysis.json").read_text())
    sg_primary = sorted(x["min_A"] for x in pj["separation_from_catalytic_site"] if "SG" in x["to"])
    sg_ok = np.allclose(sorted(sgd.values()), sg_primary, atol=1e-3)
    # SASA cross-check with Biopython
    from Bio.PDB.SASA import ShrakeRupley
    model = PDBParser(QUIET=True).get_structure("x", str(RAW / "1T49.pdb"))[0]
    chain = model["A"]
    for res in list(chain):
        if res.get_resname() in ("HOH", "MG"):
            chain.detach_child(res.id)
    try:
        sr = ShrakeRupley(probe_radius=1.4, n_points=960, radii_dict={"BR": 1.85})
    except TypeError:
        sr = ShrakeRupley(probe_radius=1.4, n_points=960)
    def prot_sasa(ch):
        sr.compute(ch, level="R")
        return {r.id[1]: r.sasa for r in ch if r.id[0] == " "}
    with_lig = prot_sasa(chain)
    apo = copy.deepcopy(chain)
    for res in list(apo):
        if res.get_resname() == "892":
            apo.detach_child(res.id)
    without = prot_sasa(apo)
    buried_bio = float(sum(without[k] - with_lig[k] for k in without))
    buried_primary = float(pj["sasa"]["protein_buried_by_ligand_A2"])
    sasa_ok = abs(buried_bio - buried_primary) / buried_primary < 0.05
    documented = {"alpha3 helix residues contacted": sorted(int(r) for r in nb[nb["within_4.0A"] & nb.resnum.between(188, 201)].resnum),
                  "alpha6 helix residues contacted": sorted(int(r) for r in nb[nb["within_4.0A"] & nb.resnum.between(263, 282)].resnum)}
    occ = pd.read_csv(RES / "ligand892_site_occupancy.csv")
    trp = occ[(occ.structure == "5K9W") & (occ.resnum == 291)].min_distance_to_superposed_ligand_A
    doc_ok = len(documented["alpha3 helix residues contacted"]) > 0 and len(documented["alpha6 helix residues contacted"]) > 0 and len(trp) == 1 and float(trp.iloc[0]) < 2.0
    record("V4_pocket", 4, "Ligand-892 neighbourhood sets, Cys215 SG separations and buried surface recomputed independently; the site is formed by "
           "alpha3/alpha6 residues and coincides with the Trp291/alpha7 position of 5K9W, as documented by Wiesmann 2004 and Keedy 2018",
           sets_ok and sg_ok and sasa_ok and doc_ok, "Independently verified (geometry); Consistent with published evidence (site identity)",
           dict(neighbourhood_sets=sets, ligand_to_Cys215_SG_min_A=dict(independent=sgd, primary=sg_primary),
                protein_SASA_buried_A2=dict(biopython_shrake_rupley=buried_bio, primary_own_implementation=buried_primary,
                                            relative_difference=abs(buried_bio - buried_primary) / buried_primary),
                documented_site_elements=documented, Trp291_min_distance_to_superposed_ligand_A=float(trp.iloc[0]),
                published_statements=["Wiesmann et al. 2004 (abstract): crystal structures 'reveal a novel site located approximately 20 A from the catalytic site'",
                                      "Keedy et al. 2018: BB compounds bind 'the space normally occupied by the regulatory C-terminal alpha7 helix'; 'BB2 directly displacing Trp291'"]),
           "brute-force distance matrix on legacy PDB coordinates; Bio.PDB.SASA.ShrakeRupley (960 points, probe 1.4 A)")

    # ---- 5. comparison with published values -------------------------------------------------
    rd = pd.read_csv(RES / "region_distances.csv")
    def val(s, name):
        v = rd[(rd.structure == s) & (rd.distance == name)].value_A
        return float(v.iloc[0]) if len(v) else None
    cc = "Asp181 CA - Cys215 CA"
    lig_sg = min(sgd.values())
    lig_ploop = [x["min_A"] for x in pj["separation_from_catalytic_site"] if x["to"].startswith("P-loop")][0]
    comp = [
        dict(published="Wiesmann 2004 abstract: allosteric site 'approximately 20 A from the catalytic site'", computed=f"ligand 892 to Cys215 SG: minimum {lig_sg:.1f} A, centroid {pj['separation_from_catalytic_site'][0]['centroid_A']:.1f} A",
             verdict="Consistent with published evidence", consistent=bool(18 <= lig_sg <= 26)),
        dict(published="Keedy 2018: BB2 'binds to an allosteric site >12 A away from the active site'", computed=f"minimum ligand-892 to P-loop (214-221) heavy-atom distance {lig_ploop:.1f} A",
             verdict="Consistent with published evidence", consistent=bool(lig_ploop > 12)),
        dict(published="5K9W / 5K9V deposited titles: 'closed state' / 'open state' (Choy 2017)", computed=f"Asp181 CA-Cys215 CA: 5K9W {val('5K9W', cc):.2f} A, 5K9V {val('5K9V', cc):.2f} A; loop-window RMSD 3.14 A",
             verdict="Consistent with published evidence", consistent=bool(val("5K9V", cc) - val("5K9W", cc) > 3)),
        dict(published="Wiesmann 2004 abstract: allosteric inhibitors 'prevent formation of the active form of the enzyme by blocking mobility of the catalytic loop'",
             computed=f"1T49 loop window matches open 5K9V (RMSD 0.33 A) and differs from closed 5K9W (2.98 A); Asp181 CA-Cys215 CA {val('1T49', cc):.2f} A",
             verdict="Consistent with published evidence for the open loop in the inhibitor complex; 'blocking mobility' is a dynamic claim that static coordinates cannot test",
             consistent=True),
        dict(published="Case-study reference values as transcribed in sources/case/interpretation.md: 12.3 A (1T49) and 8.3 A (1SUG); atom definition not stated in material available here",
             computed=f"Asp181 CA-Cys215 CA: 1T49 {val('1T49', cc):.3f} A" + (f", 1SUG {val('1SUG', cc):.3f} A" if val("1SUG", cc) else ", 1SUG not available"),
             verdict="Crystal reference distances reproduced under an inferred atom definition; the reported 12.5 A model value cannot be checked (no coordinates released)",
             consistent=bool(abs(val("1T49", cc) - 12.3) < 0.06)),
    ]
    record("V5_published", 5, "Computed differences compared with published statements", all(c["consistent"] for c in comp),
           "Consistent with published evidence", comp, "values read from results tables; published statements quoted from PubMed abstracts / open full text")

    # ---- 6. discrepancies ------------------------------------------------------------------------
    disc = [
        dict(issue="alpha7 comparison impossible", detail="Residues 285-296 have coordinates only in 5K9W (5K9V ends at 280, 1T49 at 282). No alpha7 displacement or order-disorder transition is measurable from these three entries.", status="unresolved (data limitation)"),
        dict(issue="fit set contains mobile residues", detail="Residues 238-243 (Lys239 up to ~5.9 A) and 62, 116 exceed 2 A against 5K9W although they are inside the declared core fit set. An iteratively pruned fit changes the loop RMSD by <= 0.02 A.", status="quantified; conclusion unchanged"),
        dict(issue="apo state is not a single loop state", detail="The supplementary apo entry 1SUG has a closed loop (Asp181 CA-Cys215 CA 8.30 A) whereas apo 5K9V is open (12.85 A).", status="recorded; argues against equating ligand state with loop state"),
        dict(issue="SASA implementations differ slightly", detail=f"Own implementation {buried_primary:.1f} A^2 vs Biopython {buried_bio:.1f} A^2 for protein surface buried by ligand 892.", status="within 5 % tolerance"),
        dict(issue="ligand occupancy", detail="Ligand 892 is deposited at occupancy 0.70 and Cys215 SG has two conformers (0.60/0.40) in 1T49; distances are reported for both SG positions.", status="recorded"),
        dict(issue="crystal packing not evaluated", detail="Symmetry mates were not generated; 5K9W and 1T49 are P 31 2 1 whereas 5K9V is P 32 2 1, so lattice environments differ.", status="unresolved"),
        dict(issue="case-study prediction not reproducible", detail="No prediction coordinates accompany the Tetra-1 case study and the landing page returned no readable text; no structure-prediction backend was run here.", status="not reproduced"),
    ]
    record("V6_discrepancies", 6, "Discrepancies and unresolved issues recorded", True, "Recorded", disc)

    # ---- 7. figures correspond to tables ------------------------------------------------------------
    man = json.loads((FIG / "figure_manifest.json").read_text())
    ev, ok = {}, True
    for name, m in man.items():
        hashes_ok = all(hashlib.sha256((ROOT / s).read_bytes()).hexdigest() == h for s, h in m["source_tables"].items())
        exists = (ROOT / m["file"]).exists() and (ROOT / m["file"]).stat().st_size > 10000
        ev[name] = dict(png_exists=exists, source_tables_unchanged_since_plot=hashes_ok, sources=list(m["source_tables"]))
        ok &= hashes_ok and exists
    k2 = man["fig2_rmsd_summary"]["key_values"]
    c = prim[prim.fit_definition == "core_2-280_excl_176-187"]
    vals_ok = all(abs(k2[f"{r.mobile}->{r.reference}"]["loop_176_187_rmsd_fitted_frame_A"] - r.loop_176_187_rmsd_fitted_frame_A) < 1e-9 and
                  abs(k2[f"{r.mobile}->{r.reference}"]["asp181_CA_displacement_A"] - r.asp181_CA_displacement_A) < 1e-9 for r in c.itertuples())
    k7 = man["fig7_region_distances"]["key_values"]
    vals_ok &= abs(k7[f"1T49|{cc}"] - val("1T49", cc)) < 1e-9 and man["fig5_ligand892_neighbourhood"]["key_values"]["n_within_4A"] == int(nb["within_4.0A"].sum())
    ev["plotted_values_equal_table_values"] = bool(vals_ok)
    record("V7_figures", 7, f"All {len(man)} figures exist, their source tables are byte-identical to those hashed at plot time, and plotted key values equal the table values",
           ok and vals_ok, "Independently verified", ev, "figures/figure_manifest.json hashes and key values vs current tables")

    # ---- 8. re-execution ----------------------------------------------------------------------------
    if rerun:
        tables = sorted(list(RES.glob("*.csv")) + list(RES.glob("*.json")) + [ROOT / "structure_metadata.json", ROOT / "structure_mapping.csv"])
        before = {str(p.relative_to(ROOT)): hashlib.sha256(p.read_bytes()).hexdigest() for p in tables}
        logs = {}
        for script in ("structure_alignment.py", "allosteric_pockets.py", "contact_analysis.py", "make_figures.py"):
            pr = subprocess.run([sys.executable, str(ROOT / "analysis" / script)], capture_output=True, text=True, cwd=str(ROOT))
            logs[script] = dict(returncode=pr.returncode, stderr_tail=pr.stderr[-300:])
        after = {k: hashlib.sha256((ROOT / k).read_bytes()).hexdigest() for k in before}
        changed = [k for k in before if before[k] != after[k]]
        record("V8_rerun", 8, f"The four analysis scripts were re-executed in fresh interpreter processes; {len(before) - len(changed)} of {len(before)} "
               "result tables were reproduced byte-for-byte", all(l["returncode"] == 0 for l in logs.values()) and not changed, "Independently reproduced",
               dict(scripts=logs, n_tables=len(before), changed_tables=changed, python=sys.version.split()[0]),
               "subprocess re-execution with the documented environment (environment.json); SHA-256 of every result table before vs after")
    else:
        record("V8_rerun", 8, "Re-execution not requested in this invocation (use --rerun)", True, "Not run", {})

    import Bio, scipy, matplotlib
    env = dict(python=sys.version, platform=platform.platform(), numpy=np.__version__, scipy=scipy.__version__, pandas=pd.__version__,
               biopython=Bio.__version__, matplotlib=matplotlib.__version__)
    (ROOT / "environment.json").write_text(json.dumps(env, indent=1))
    out = dict(generated_utc=datetime.now(timezone.utc).isoformat(), n_tests=len(TESTS), n_pass=sum(t["status"] == "pass" for t in TESTS),
               environment=env, tests=TESTS)
    (ROOT / "verification_results.json").write_text(json.dumps(out, indent=1, default=str))
    print(f"{out['n_pass']}/{out['n_tests']} checks passed")
    return out


if __name__ == "__main__":
    main(rerun="--rerun" in sys.argv)
