import io
import os

os.chdir(r"C:/Users/decid/Documents/projects/spt-core/.worktrees/hertz-inbound-probe")
P = "crates/spt-daemon/tests/twohost_web.rs"
s = io.open(P, encoding="utf-8", newline="").read()
CR, LF = chr(13), chr(10)
CRLF = s.count(CR + LF) > s.count(LF) // 2


def term(t):
    return t.replace(CR + LF, LF).replace(LF, CR + LF) if CRLF else t.replace(CR + LF, LF)


# ── A: the ack goes to B's BEACON PORT, not to `from`.
old = """                // OUT OF THE BEACON SOCKET, not this one: an ack sent from the
                // listening port would write return state for the very tuple the
                // next run must find cold, so the guard would poison its own
                // next measurement at the end of every run, green or red.
                if let Err(e) = beacon_socket.send_to(PROBE_ACK, from) {"""
new = """                // OUT OF THE BEACON SOCKET, not this one: an ack sent from the
                // listening port would write return state for the very tuple the
                // next run must find cold, so the guard would poison its own
                // next measurement at the end of every run, green or red.
                //
                // AND ADDRESSED TO B'S BEACON PORT, not to `from`. MEASURED
                // 2026-09-09: acking to `from` (B's ephemeral probe port) leaves
                // A's ack unsolicited at B — it comes from this ephemeral socket,
                // not from the port B dialled, so it matches no return state B
                // opened — and a receiver whose inbound rule is a fixed port
                // RANGE drops it. B then reported INBOUND_BLOCKED on a link its
                // own peer had just certified: the A-side said INBOUND OK and the
                // B-side said blocked, in the same run. The rig's port range is
                // the only inbound address B can be reached on cold, so the ack
                // uses it, and B reads the ack on the socket it already binds.
                if let Err(e) = beacon_socket.send_to(PROBE_ACK, beacon_target) {"""
old, new = term(old), term(new)
assert s.count(old) == 1
s = s.replace(old, new)

# ── B: the ack lands on the FIXED socket (the one it already binds for beacons).
old_recv = """        match probe_socket.recv_from(&mut buf) {
            Ok((n, from)) if buf[..n] == *PROBE_ACK => {"""
new_recv = """        // The ack arrives on the FIXED socket, not the ephemeral sender: A sends
        // it to this host's rig port so it is addressable cold (see A's cell).
        match socket.recv_from(&mut buf) {
            Ok((n, from)) if buf[..n] == *PROBE_ACK => {"""
old_recv, new_recv = term(old_recv), term(new_recv)
assert s.count(old_recv) == 1
s = s.replace(old_recv, new_recv)

io.open(P, "w", encoding="utf-8", newline="").write(s)
print("ack path: A -> B's rig port, read on B's fixed socket")
