import json, subprocess, pathlib, time, re
LANE = pathlib.Path(r"C:/Users/decid/Documents/projects/spt-core/.worktrees/304-fold-admission")
T = "crates/spt-daemon/src/bootstrap_firewall/windows.rs"
OUT = pathlib.Path(r"C:/Users/decid/AppData/Local/Temp/claude/C--Users-decid-Documents-projects-spt-core/d4e86801-8514-4527-94e1-84f30b0d84d9/scratchpad")
PROG = "bootstrap_firewall::windows::tests::a_program_bearing_rule_does_not_satisfy_a_spec_that_wants_no_program_filter"
REMOTE = "bootstrap_firewall::windows::tests::an_unrestricted_remote_does_not_satisfy_a_narrowed_spec"

def run(a):
    p = subprocess.run(a, cwd=LANE, capture_output=True, text=True)
    return p.returncode, p.stdout, p.stderr

def shape():
    raw = (LANE / T).read_bytes(); c = raw.count(b"\r\n")
    _, w, _ = run(["git", "hash-object", T]); _, h, _ = run(["git", "rev-parse", f"HEAD:{T}"])
    return {"bytes": len(raw), "crlf": c, "bare_lf": raw.count(b"\n") - c,
            "work": w.strip(), "head": h.strip(), "clean": w.strip() == h.strip()}

def mutate(anchor, repl):
    raw = (LANE / T).read_bytes()
    eol = b"\r\n" if raw.count(b"\r\n") else b"\n"
    a = anchor.encode().replace(b"\n", eol); r = repl.encode().replace(b"\n", eol)
    n = raw.count(a)
    if n != 1:
        return False, f"ANCHOR COUNT {n} (need 1) — ABORT, no mutation"
    (LANE / T).write_bytes(raw.replace(a, r, 1)); return True, "mutated"

def arm(label, cell):
    t0 = time.time()
    rc, o, e = run(["cargo", "nextest", "run", "-p", "spt-daemon", "--lib", "--no-fail-fast",
                    "--success-output", "immediate", "-E", f"test(={cell})"])
    body = o + e
    (OUT / f"pred-{label}.raw").write_text(body, encoding="utf-8", errors="replace")
    summ = next((l.strip() for l in body.splitlines() if "tests run:" in l or "test run:" in l), "NO SUMMARY")
    ran = re.search(r"(\d+) tests? run", summ)
    line = next((l.strip() for l in body.splitlines() if "panicked at" in l), "NO PANIC LINE")
    msg = [l.strip() for l in body.splitlines() if "assertion" in l or "left:" in l or "right:" in l][:4]
    run(["git", "checkout", "--", T])
    return {"label": label, "exit": rc, "secs": round(time.time() - t0, 1), "summary": summ,
            "ran": int(ran.group(1)) if ran else None, "panic": line, "msg": msg, "revert": shape()}

rep = {"sha": run(["git", "rev-parse", "HEAD"])[1].strip(), "pre": shape(), "arms": []}
print("SUBJECT", rep["sha"], json.dumps(rep["pre"]), flush=True)
for label, anchor, repl, cell in [
    ("p1-program", "    if !program_ok {", "    if false {", PROG),
    ("p2-profile", "    if observed.profile != want.profile {", "    if false {", REMOTE),
    ("p3-remote", "    seen == wanted\n}", "    true\n}", REMOTE),
]:
    ok, m = mutate(anchor, repl)
    print(label, "mutate:", m, flush=True)
    if ok:
        a = arm(label, cell); rep["arms"].append(a); print(label.upper(), json.dumps(a), flush=True)
    else:
        rep["arms"].append({"label": label, "aborted": m})
rep["post"] = shape()
print("POST", json.dumps(rep["post"]), flush=True)
(OUT / "pred-report.json").write_text(json.dumps(rep, indent=2), encoding="utf-8")
print("DONE", flush=True)
