#!/usr/bin/env python3
"""Run the W-1 arms in doyle's order: E3, E4 (red-first mutations), E1', E2'."""
import json, sys, pathlib
sys.path.insert(0, r"C:/Users/decid/AppData/Local/Temp/claude/C--Users-decid-Documents-projects-spt-core/d4e86801-8514-4527-94e1-84f30b0d84d9/scratchpad")
from w1driver import LANE, TARGET, OUT, run, shape, mutate, revert, nextest, summary_line

FIVE = [
    "the_admission_is_written_for_the_bound_port_and_never_the_configured_one",
    "the_admission_is_scoped_by_port_and_remote_and_carries_no_program",
    "an_unelevated_write_refuses_loudly_and_the_listener_keeps_serving",
    "ownership_covers_our_rule_only_and_a_residual_is_named_not_swallowed",
    "the_ci_gate_stops_the_effector_before_it_touches_the_host",
]
FILTER = " | ".join(f"test(={'firewall::tests::' + n})" for n in FIVE)

report = {"sha": run(["git", "rev-parse", "HEAD"])[1].strip(), "arms": []}
print("SUBJECT", report["sha"], flush=True)
print("PRE-ARM SHAPE", json.dumps(shape(TARGET)), flush=True)

# ---- E3: u2-R, program= injected. PREDICTED GREEN (the assertion is vacuous).
ok, msg = mutate(
    TARGET,
    "protocol=TCP localport={port} profile=any remoteip={LAN_REMOTE_TAILNET} & \\",
    "protocol=TCP localport={port} profile=any remoteip={LAN_REMOTE_TAILNET} program=C:\\\\fake\\\\spt.exe & \\",
)
print("E3 mutate:", msg, flush=True)
if ok:
    r = nextest("e3-u2R", ["--success-output", "immediate", "-E", f"test(=firewall::tests::{FIVE[1]})"])
    r["summary"] = summary_line(r["body"])
    r["revert"] = revert(TARGET)
    del r["body"]
    report["arms"].append(r)
    print("E3", json.dumps(r), flush=True)
else:
    report["arms"].append({"label": "e3-u2R", "aborted": msg})
    print("E3 ABORTED — no mutation, no arm", flush=True)

# ---- E4: u1-R, the command built from the resolved port. PREDICTED RED.
ok, msg = mutate(
    TARGET,
    "pub fn lan_admission_fix(port: u16) -> String {\n    format!(",
    "pub fn lan_admission_fix(port: u16) -> String {\n    let port = DEFAULT_LAN_BOOTSTRAP_PORT_MUTANT;\n    format!(",
)
print("E4 mutate:", msg, flush=True)
if ok:
    # the mutant constant, defined beside the function so the arm compiles
    p = LANE / TARGET
    raw = p.read_bytes()
    eol = b"\r\n" if raw.count(b"\r\n") > 0 else b"\n"
    anchor = b"pub fn lan_admission_fix(port: u16) -> String {"
    const = (b"const DEFAULT_LAN_BOOTSTRAP_PORT_MUTANT: u16 = 5470;" + eol
             + b"pub fn lan_admission_fix(port: u16) -> String {")
    p.write_bytes(raw.replace(anchor, const, 1))
    r = nextest("e4-u1R", ["--success-output", "immediate", "-E", f"test(=firewall::tests::{FIVE[0]})"])
    r["summary"] = summary_line(r["body"])
    tail = [l for l in r["body"].splitlines() if "assertion" in l or "left" in l or "right" in l or "panicked" in l]
    r["assertion_lines"] = tail[:12]
    r["revert"] = revert(TARGET)
    del r["body"]
    report["arms"].append(r)
    print("E4", json.dumps(r), flush=True)
else:
    report["arms"].append({"label": "e4-u1R", "aborted": msg})
    print("E4 ABORTED — no mutation, no arm", flush=True)

# ---- E1': the five, clean tree, immediate output.
r = nextest("e1-five", ["--success-output", "immediate", "-E", FILTER])
r["summary"] = summary_line(r["body"])
r["u3_lines"] = [l for l in r["body"].splitlines() if "SERVING" in l or "ACL" in l][:6]
del r["body"]
report["arms"].append(r)
print("E1'", json.dumps(r), flush=True)

# ---- E2': unfiltered, plus the list count on the SAME tip.
rc, out, err = run(["cargo", "nextest", "list", "-p", "spt-daemon", "--lib"])
listed = [l for l in out.splitlines() if l.strip().startswith("spt-daemon ")]
r = nextest("e2-unfiltered", [])
r["summary"] = summary_line(r["body"])
r["list_total"] = len(listed)
r["failed_lines"] = [l for l in r["body"].splitlines() if "FAIL" in l][:10]
r["leaky"] = [l.strip() for l in r["body"].splitlines() if "LEAK" in l][:12]
del r["body"]
report["arms"].append(r)
print("E2'", json.dumps(r), flush=True)

print("FINAL SHAPE", json.dumps(shape(TARGET)), flush=True)
(OUT / "w1-report.json").write_text(json.dumps(report, indent=2), encoding="utf-8")
print("REPORT WRITTEN", flush=True)
