#!/usr/bin/env python3
"""E152 tamper fixtures: each forgery applied to a copy of the bundle must make the offline verifier fail.
  python3 -I verify_tamper_e152.py <bundle_dir>   (prints JSON; exit 0 only if the clean bundle passes and every forgery fails)
"""
import json, shutil, subprocess, sys, tempfile
from pathlib import Path

B = Path(sys.argv[1] if len(sys.argv) > 1 else ".").resolve()
V = B / "verify_e152_offline.py"


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


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


def mem_break(p):
    edit_json(p, lambda d: d[next(iter(d))][-1].__setitem__("prev", "f" * 64) if d[next(iter(d))] else None)


FIX = {"flip_a_confirmation_discovery": ("confirm/confirmation_rows.jsonl", flip_row),
       "change_P1_result": ("analysis.json", lambda p: edit_json(p, lambda d: d["hypotheses"]["P1"].__setitem__("p_dense", 0.0001) if "p_dense" in d["hypotheses"]["P1"] else d["hypotheses"]["P1"].__setitem__("verdict", "SUPPORTED"))),
       "promote_in_snapshot": ("e152-snapshot.json", lambda p: edit_json(p, lambda d: d.__setitem__("promotion", "PROMOTED" if d["promotion"] != "PROMOTED" else "NOT_PROMOTED"))),
       "edit_preregistration": ("preregistration.json", lambda p: edit_json(p, lambda d: d["confirmation"]["populations"].__setitem__("bool", 399))),
       "break_memory_chain": ("development/memory_chains.json", mem_break),
       "edit_library_chain": ("development/library_public.json", lambda p: edit_json(p, lambda d: [es[-1].__setitem__("prev", "e" * 64) for es in d.values() if es])),
       "swap_frozen_arm": ("confirm/arms.json", lambda p: edit_json(p, lambda d: d["arms"]["A"].__setitem__("source_sha256", "0" * 64))),
       "hide_spend": ("development/api_ledger.jsonl", lambda p: p.write_text("".join(l + "\n" for l in p.read_text().splitlines()[1:])))}


def verify(d):
    return subprocess.run([sys.executable, "-I", str(d / "verify_e152_offline.py"), str(d)], capture_output=True, text=True).returncode == 0


res = {"baseline_passes": verify(B)}
for name, (rel, f) in FIX.items():
    with tempfile.TemporaryDirectory() as t:
        d = Path(t) / "b"; shutil.copytree(B, d); before = (d / rel).read_bytes(); f(d / rel)
        res[name] = "NOT_APPLICABLE" if (d / rel).read_bytes() == before else ("REJECTED" if not verify(d) else "ACCEPTED (BAD)")
res["all_rejected"] = all(v in ("REJECTED", "NOT_APPLICABLE") for k, v in res.items() if k not in ("baseline_passes",)) and any(v == "REJECTED" for v in res.values())
print(json.dumps(res, indent=1)); sys.exit(0 if res["baseline_passes"] and res["all_rejected"] else 1)
