import io, hashlib, subprocess, os, sys

W = r"C:/Users/decid/Documents/projects/spt-core/.worktrees/conduit-w2"
SRC = W + "/crates/spt-daemon/src/shellwake.rs"
POOL = r"C:/Users/decid/Documents/projects/spt-core/.worktrees/now-signal-inproc-daemon/target"

orig = io.open(SRC, encoding="utf-8").read()
base_sha = hashlib.sha256(orig.encode("utf-8")).hexdigest()
print("baseline sha256", base_sha)

MUTS = {
    # A: LEVEL trigger instead of EDGE. The third arm (a freshly stranded
    # instance under a still-online owner) must go RED.
    "A_level_not_edge": (
        "            if online && !self.seen.get(&owner).copied().unwrap_or(false) {",
        "            if online {",
    ),
    # B: drop the corpse-boot refusal from the SHARED body. The negative arm
    # (force-killed THIS boot) must go RED.
    "B_no_predates_boot_arm": (
        "        if !launch_predates_boot(launch.launched_ms, boot_ms, BOOT_RESTORE_SLACK_MS) {",
        "        if false {",
    ),
}

env = dict(os.environ, CARGO_TARGET_DIR=POOL)
results = {}
for name, (old, new) in MUTS.items():
    n = orig.count(old)
    print(f"[{name}] anchor occurrences: {n}")
    if n != 1:
        results[name] = f"ANCHOR-COUNT-{n} (not applied)"
        continue
    io.open(SRC, "w", encoding="utf-8", newline="").write(orig.replace(old, new, 1))
    applied = hashlib.sha256(io.open(SRC, encoding="utf-8").read().encode("utf-8")).hexdigest()
    assert applied != base_sha, "mutation did not change the file"
    raw = W + f"/W2_mut_{name}.raw"
    with io.open(raw, "w", encoding="utf-8", newline="") as fh:
        p = subprocess.run(
            ["cargo", "nextest", "run", "-p", "spt-daemon",
             "-E", "test(an_owner_coming_online_after_a_spent_sweep_restores_only_its_restart_casualty)",
             "--no-fail-fast"],
            cwd=W, env=env, stdout=fh, stderr=subprocess.STDOUT, text=True)
    io.open(W + f"/W2_mut_{name}.exit", "w", newline="").write(str(p.returncode))
    results[name] = f"exit={p.returncode}"
    print(f"[{name}] leg exit {p.returncode}")
    io.open(SRC, "w", encoding="utf-8", newline="").write(orig)

restored = hashlib.sha256(io.open(SRC, encoding="utf-8").read().encode("utf-8")).hexdigest()
print("restored sha256", restored, "IDENTICAL" if restored == base_sha else "MISMATCH")
assert restored == base_sha
print("RESULTS:", results)
