#!/usr/bin/env python3
"""E150 tamper fixtures: each fixture modifies a copy of the sealed bundle and must make the offline verifier fail.

  python3 tamper_fixtures.py <bundle_dir> <out.json>
"""
import json, shutil, subprocess, sys, tempfile
from pathlib import Path


def edit_json(p, fn):
    d = json.loads(p.read_text()); fn(d); p.write_text(json.dumps(d, indent=1, sort_keys=True))


def flip_row(p):
    lines = p.read_text().splitlines()
    r = json.loads(lines[0]); r["discovery"] = not r["discovery"]
    lines[0] = json.dumps(r, sort_keys=True, separators=(",", ":"))
    p.write_text("\n".join(lines) + "\n")


def corrupt_sig(p):
    lines = p.read_text().splitlines()
    r = json.loads(lines[1]); s = r["signature"]; r["signature"] = ("0" if s[0] != "0" else "1") + s[1:]
    lines[1] = json.dumps(r, sort_keys=True, separators=(",", ":"))
    p.write_text("\n".join(lines) + "\n")


def rehash_manifest(b):  # tamper a file AND update its manifest hash (signature must then fail)
    flip_row(b / "raw/rows.jsonl")
    import hashlib
    edit_json(b / "MANIFEST.json", lambda m: m["files"].__setitem__("raw/rows.jsonl", hashlib.sha256((b / "raw/rows.jsonl").read_bytes()).hexdigest()))


FIXTURES = {
    "data: flip one discovery in raw rows": lambda b: flip_row(b / "raw/rows.jsonl"),
    "source: edit a researcher genome in chains.json": lambda b: edit_json(b / "chains/chains.json", lambda d: d["researchers"]["C3"].__setitem__("n_prop", d["researchers"]["C3"]["n_prop"] + 1)),
    "lineage: forge a parent hash": lambda b: edit_json(b / "chains/chains.json", lambda d: d["generations"][1].__setitem__("parent_hash", "0" * 64)),
    "statistics: change the H1 verdict in analysis.json": lambda b: edit_json(b / "analysis.json", lambda d: d["H1"].__setitem__("verdict", "SUPPORTED" if d["H1"]["verdict"] != "SUPPORTED" else "INCONCLUSIVE")),
    "signature: corrupt one evaluator row signature": lambda b: corrupt_sig(b / "raw/rows.jsonl"),
    "manifest: tamper a file and rewrite its manifest hash": rehash_manifest,
    "snapshot: flip the public promotion decision": lambda b: edit_json(b / "e150-snapshot.json", lambda d: d.__setitem__("promotion", "PROMOTED" if d["promotion"] != "PROMOTED" else "NOT_PROMOTED")),
}


def main():
    src, out = Path(sys.argv[1]), Path(sys.argv[2])
    ver = src / "verify_e150_offline.py"
    base = subprocess.run([sys.executable, "-I", str(ver), str(src)], capture_output=True, text=True)
    res = {"baseline_passes": base.returncode == 0, "fixtures": []}
    for name, fn in FIXTURES.items():
        with tempfile.TemporaryDirectory() as td:
            b = Path(td) / "b"; shutil.copytree(src, b); fn(b)
            r = subprocess.run([sys.executable, "-I", str(ver), str(b)], capture_output=True, text=True)
            failed = [l[5:] for l in r.stdout.splitlines() if l.startswith("FAIL ")]
            res["fixtures"].append({"fixture": name, "rejected": r.returncode != 0, "failed_checks": failed[:4]})
    res["all_rejected"] = all(f["rejected"] for f in res["fixtures"])
    out.write_text(json.dumps(res, indent=1))
    print(json.dumps({"baseline_passes": res["baseline_passes"], "all_rejected": res["all_rejected"], "n": len(res["fixtures"])}))
    return 0 if res["baseline_passes"] and res["all_rejected"] else 1


if __name__ == "__main__":
    sys.exit(main())
