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"
NEW = r"C:/Users/decid/AppData/Local/Temp/claude/C--Users-decid-Documents-projects-spt-core/65856f58-c970-4897-9023-c63a91d71696/scratchpad/probe/newblock.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)


# 1. cut the whole probe block out of the place it must not be.
start_marker = "// \u2550\u2550 THE INBOUND PROBE"
i = s.index(start_marker)
end_anchor = "fn two_host_inbound_probe_role_b"
j = s.index(end_anchor, i)
# end of that fn = the first line that is exactly a closing brace at column 0
k = s.index(term(LF + "}" + LF), j) + len(term(LF + "}" + LF))
old_block = s[i:k]
s = s[:i] + s[k:]

# the cut leaves the role_b doc block + its two tags directly above `fn
# two_host_web_role_b` again; assert that rather than trusting it.
tags = term("// [int->REQ-WEB-CROSS-NODE-PROXY]" + LF + "// [int->REQ-WEB-ACCESS-SURFACE]" + LF)
assert tags in s, "role_b tags not found after the cut"
after_tags = s[s.index(tags) + len(tags):]
assert after_tags.lstrip().startswith("#[test]"), (
    "tags do not bind to a #[test] after the cut: " + after_tags[:80]
)

# 2. new magics beside the existing one.
magic = term('const PROBE_MAGIC: &[u8] = b"SPT-TWOHOST-INBOUND-PROBE-v1";' + LF)
assert s.count(magic) == 1
magics = magic + term(
    "/// A's liveness beacon, A\u2192B. Distinct from the probe and the ack because a"
    + LF
    + "/// listener that cannot tell them apart is a clock that never starts."
    + LF
    + 'const PROBE_BEACON: &[u8] = b"SPT-TWOHOST-INBOUND-BEACON-v1";'
    + LF
    + "/// A's receipt, A\u2192B, and B's fast green."
    + LF
    + 'const PROBE_ACK: &[u8] = b"SPT-TWOHOST-INBOUND-ACK-v1";'
    + LF
)
s = s.replace(magic, magics)

# 3. paste the rewritten block ABOVE the Role B rule line, where it documents
#    nothing but itself.
rule = term("// \u2500\u2500 Role B: the owner")
r = s.index(rule)
new_block = io.open(NEW, encoding="utf-8", newline="").read()
s = s[:r] + term(new_block) + term(LF) + s[r:]

io.open(P, "w", encoding="utf-8", newline="").write(s)
print("spliced. old block bytes:", len(old_block), "-> new:", len(new_block))
