#!/usr/bin/env python3
"""Run the pipeline twice and compare the sha256 of every generated file.

Writes results/reproducibility_check.json, then rebuilds REPORT.md so that it cites the outcome.
"""
import contextlib, hashlib, io, json, pathlib, runpy

ROOT = pathlib.Path(__file__).resolve().parents[1]
STEPS = ("01_build_curated_data.py", "02_verify_sources.py", "03_analysis.py", "04_figures.py", "05_build_report.py")
OUT = ROOT / "results" / "reproducibility_check.json"

def run():
    with contextlib.redirect_stdout(io.StringIO()):
        for s in STEPS:
            runpy.run_path(str(ROOT / "code" / s), run_name="__main__")
    files = [ROOT / "REPORT.md"]
    for d in ("data/curated", "data/published_benchmarks", "results", "figures"):
        files += sorted(p for p in (ROOT / d).iterdir() if p.is_file() and p != OUT)
    return {str(p.relative_to(ROOT)): hashlib.sha256(p.read_bytes()).hexdigest() for p in files}

a, b = run(), run()
diff = sorted(k for k in a if a[k] != b.get(k))
OUT.write_text(json.dumps({
    "description": "sha256 of every generated file after two consecutive full runs of the pipeline in the same environment",
    "n_files_compared": len(a), "n_identical": len(a) - len(diff), "files_differing": diff}, indent=2), encoding="utf-8")
with contextlib.redirect_stdout(io.StringIO()):
    runpy.run_path(str(ROOT / "code" / "05_build_report.py"), run_name="__main__")
print(f"{len(a) - len(diff)} of {len(a)} generated files byte-identical across two runs; differing: {diff}")
