import io, os, sys
SP = os.path.dirname(os.path.abspath(__file__))
p = 'crates/spt/src/wansend.rs'
raw = io.open(p, encoding='utf-8', newline='').read()
crlf = '\r\n' in raw
s = raw.replace('\r\n', '\n')
block = io.open(os.path.join(SP, 'w3_wansend_block.rs'), encoding='utf-8').read().replace('\r\n', '\n')
anchor = "/// `regs` with this node's row for `id` replaced by the local perch's view, in every\n"
assert s.count(anchor) == 1
s = s.replace(anchor, block + anchor)


def rep(old, new):
    global s
    assert s.count(old) == 1, (old[:80], s.count(old))
    s = s.replace(old, new)


rep('''    sender_origin: Option<&str>,
    body: &str,
) -> WanSendOutcome {
    let own_hex = match spt_store::nodeid::load_or_create() {''', '''    sender_origin: Option<&str>,
    body: &str,
    handoff: bool,
) -> WanSendOutcome {
    let own_hex = match spt_store::nodeid::load_or_create() {''')
rep('''        body,
        &op_id,
        seed_first_addr,
    )''', '''        body,
        &op_id,
        handoff,
        seed_first_addr,
    )''')
rep('''    body: &str,
    op_id: &str,
    resolver: impl Fn(&str) -> Option<serde_json::Value>,
) -> WanSendOutcome {''', '''    body: &str,
    op_id: &str,
    handoff: bool,
    resolver: impl Fn(&str) -> Option<serde_json::Value>,
) -> WanSendOutcome {''')
rep('''        sender_origin: sender_origin.map(str::to_string),
        handoff: false,
    };''', '''        sender_origin: sender_origin.map(str::to_string),
        // [impl->REQ-INSTANCE-HANDOFF]
        handoff,
    };''')
rep('''        O::PeerSilent => WanSendOutcome::PeerSilent { node },
    }''', '''        O::PeerSilent => WanSendOutcome::PeerSilent { node },
        // Only a handoff sender can receive it (REQ-INSTANCE-HANDOFF).
        // [impl->REQ-INSTANCE-HANDOFF]
        O::HandoffTaken => WanSendOutcome::Sent {
            node,
            how: "handoff",
        },
    }''')
if crlf:
    s = s.replace('\n', '\r\n')
io.open(p, 'w', encoding='utf-8', newline='').write(s)
print('ok')
