"""Mutation harness. Each entry breaks ONE behaviour; the named tests must then FAIL.

A mutation whose anchor misses applies nothing and the suite stays green — which reads exactly
like "the test caught it". So every anchor is asserted to match exactly once before the run, and a
missed anchor is a hard error, never a pass.
"""
import io
import subprocess
import sys

P = r"C:\Users\decid\Documents\projects\spt-claude-code\tools\claude-spt\src\hook.rs"
MANIFEST = r"C:\Users\decid\Documents\projects\spt-claude-code\tools\claude-spt\Cargo.toml"

MUTATIONS = [
    (
        "M1 instrument keying restored (the defect itself)",
        """fn handle_post_tool_use(env: &mut dyn HookEnv, v: &Value) {
    let cwd = hook_cwd(v);""",
        """fn handle_post_tool_use(env: &mut dyn HookEnv, v: &Value) {
    if field(v, "tool_name") != "Write" { return; }
    let cwd = hook_cwd(v);""",
        ["a_commune_drop_arms_whichever_tool_wrote_it"],
    ),
    (
        "M2 stamp guard removed (state trigger re-fires)",
        """    if env.read_adapter_state(&rel).as_deref() == Some(stamp.as_str()) {
        return None;
    }""",
        """    if false {
        return None;
    }""",
        [
            "one_drop_arms_exactly_once_across_every_leg_and_every_hook",
            "an_unchanged_drop_is_stat_but_never_re_read",
            "a_drop_without_the_wake_marker_never_arms_and_is_read_once",
        ],
    ),
    (
        "M3 stamp records ARMED, not EXAMINED (marker-less drop re-read forever)",
        """    let body = env.read_file_tail(&path, 0).map(|(c, _)| c).unwrap_or_default();
    env.write_adapter_state(&rel, &stamp);
    if !has_wake_marker(&body) {
        return None;
    }""",
        """    let body = env.read_file_tail(&path, 0).map(|(c, _)| c).unwrap_or_default();
    if !has_wake_marker(&body) {
        return None;
    }
    env.write_adapter_state(&rel, &stamp);""",
        ["a_drop_without_the_wake_marker_never_arms_and_is_read_once"],
    ),
    (
        "M4 shortcut no longer stamps its own write (double-fire through the fix)",
        "        stamp_commune_drop(env, &shortcut_cwd, id);",
        "",
        ["the_commune_shortcut_stamps_its_own_write_so_the_detector_does_not_arm_twice"],
    ),
    (
        "M5 Stop backstop leg deleted",
        '    arm_from_commune_drop(env, &id, &sid, &hook_cwd(v), "Stop");',
        "",
        ["the_stop_leg_arms_and_then_holds_the_quiet_window_in_one_pass"],
    ),
    (
        "M6 PreToolUse mid-turn leg deleted",
        '    arm_from_commune_drop(env, &id, &sid, &hook_cwd(v), "PreToolUse");',
        "",
        ["the_pretool_leg_arms_a_drop_no_posttooluse_ever_saw"],
    ),
    (
        "M7 stamp survives an ingested drop (a later drop reads as already examined)",
        """        if env.read_adapter_state(&rel).is_some() {
            env.write_adapter_state(&rel, "");
        }
        return None;""",
        "        return None;",
        ["an_ingested_drop_forgets_its_stamp"],
    ),
]

orig = io.open(P, encoding="utf-8").read()
fails = []
for name, old, new, tests in MUTATIONS:
    n = orig.count(old)
    if n != 1:
        print(f"ANCHOR MISS ({n}) for {name} — mutation not applied, result would be meaningless")
        fails.append(name)
        continue
    io.open(P, "w", encoding="utf-8", newline="\n").write(orig.replace(old, new, 1))
    caught = []
    for t in tests:
        r = subprocess.run(
            ["cargo", "test", "--manifest-path", MANIFEST, t],
            capture_output=True,
            text=True,
        )
        # exit 0 == the test still passed == the mutation went UNCAUGHT
        caught.append(r.returncode != 0)
        if r.returncode == 0:
            print(f"  UNCAUGHT: {t}")
    ok = all(caught)
    print(f"{'CAUGHT ' if ok else 'ESCAPED'} {name}")
    if not ok:
        fails.append(name)

io.open(P, "w", encoding="utf-8", newline="\n").write(orig)
print("\nreverted to original;", "ALL MUTATIONS CAUGHT" if not fails else f"ESCAPES: {fails}")
sys.exit(1 if fails else 0)
