import io


def rw(path, pairs):
    s = io.open(path, 'r', encoding='utf-8', newline='').read()
    out = s
    for old, new in pairs:
        assert old in out, 'anchor missing in %s: %r' % (path, old[:70])
        out = out.replace(old, new, 1)
    assert out != s
    io.open(path, 'w', encoding='utf-8', newline='').write(out)
    print('patched', path)


# ------------------------------------------------- 1. a fresh, attempt-specific isolated home
rw('_part1_header.sh', [(
    'H="$SP/fp-home-d2"                # isolated SPT_HOME, THIS experiment only. D2 SUCCESSOR:',
    'H="$SP/fp-home-d2-a2"             # isolated SPT_HOME, THIS ATTEMPT only. fp-home-d2 belongs to\n'
    '                                  # the RETAINED failed run and is PRESERVED, not reused or\n'
    '                                  # cleared: a run that adopted it could not tell its own state\n'
    '                                  # from that run\'s, and the evidence of a failure is not scratch\n'
    '                                  # space (doyle K4QDUUVV). The pre-existence refusal below is\n'
    '                                  # KEPT unchanged and now bites on a prior ATTEMPT of this\n'
    '                                  # successor rather than on anyone else\'s evidence. EARLIER:')])

# ------------------------------------------------- 2. exact whole-line acknowledgment matching
OLD_ACK = """ack_missing=''
grep -q "PREPARED" "$PREPARED_ACK" 2>/dev/null || ack_missing="$ack_missing PREPARED"
grep -q "NOT_STARTED" "$PREPARED_ACK" 2>/dev/null || ack_missing="$ack_missing NOT_STARTED"
grep -q "executable_sha256=$EXE_SHA" "$PREPARED_ACK" 2>/dev/null || ack_missing="$ack_missing executable_sha256=$EXE_SHA\""""

NEW_ACK = """ack_missing=''
# EXACT WHOLE-LINE TOKENS (doyle K4QDUUVV). A substring search for PREPARED is satisfied by
# NOT_PREPARED, and one for GO_AUTHORIZED by NOT_GO_AUTHORIZED -- so a receipt that REFUSES would
# have read as a receipt that agrees, which is the worst direction for this particular mistake.
# Matching is whole-line and the hash fields are matched entire, so a truncated or prefixed hash
# cannot satisfy one either. CR IS STRIPPED FIRST: the receipt is written by a Windows elevated
# leg, so its lines end CRLF, and a whole-line match against a line ending in \\r matches nothing --
# the tightening would otherwise have refused every honest receipt.
ack_line() { tr -d '\\r' < "$1" 2>/dev/null | grep -qx -F -- "$2"; }
ack_line "$PREPARED_ACK" "PREPARED"    || ack_missing="$ack_missing PREPARED"
ack_line "$PREPARED_ACK" "NOT_STARTED" || ack_missing="$ack_missing NOT_STARTED"
ack_line "$PREPARED_ACK" "executable_sha256=$EXE_SHA" || ack_missing="$ack_missing executable_sha256=$EXE_SHA\""""
rw('_part_main.sh', [(OLD_ACK, NEW_ACK)])

rw('_part_main.sh', [(
    """grep -q "capture_sha256=$CAPTURE_SHA" "$PREPARED_ACK" 2>/dev/null || ack_missing="$ack_missing capture_sha256=$CAPTURE_SHA\"""",
    """ack_line "$PREPARED_ACK" "capture_sha256=$CAPTURE_SHA" || ack_missing="$ack_missing capture_sha256=$CAPTURE_SHA\"""")])

rw('_part_main.sh', [(
    """grep -q "GO_AUTHORIZED" "$GO_ACK" 2>/dev/null || go_missing="$go_missing GO_AUTHORIZED"
grep -q "$GO_ACK_NONCE" "$GO_ACK" 2>/dev/null || go_missing="$go_missing nonce=$GO_ACK_NONCE\"""",
    """ack_line "$GO_ACK" "GO_AUTHORIZED" || go_missing="$go_missing GO_AUTHORIZED"
# THE NONCE KEEPS ITS SUBSTRING MATCH, deliberately: it is quoted inside a line the executor
# writes in its own words ("nonce: <value>"), and it is a run-scoped value that nothing else on
# the receipt can accidentally contain.
grep -q -F -- "$GO_ACK_NONCE" "$GO_ACK" 2>/dev/null || go_missing="$go_missing nonce=$GO_ACK_NONCE\"""")])

# the request text should ask for what the check now requires
rw('_part_main.sh', [(
    '"ACKNOWLEDGEMENT ONLY. Do not run the product. Reply in the receipt with the four tokens: PREPARED, NOT_STARTED, executable_sha256=<the sha256 you measure of "$EXE">, and capture_sha256=<the sha256 you measure of "$BIN/d2_capture.ps1">"',
    '"ACKNOWLEDGEMENT ONLY. Do not run the product. Reply in the receipt with these four tokens, EACH ON A LINE OF ITS OWN AND NOTHING ELSE ON THAT LINE: PREPARED, NOT_STARTED, executable_sha256=<the sha256 you measure of "$EXE">, capture_sha256=<the sha256 you measure of "$BIN/d2_capture.ps1">. If you are NOT prepared, say so in words -- do not write NOT_PREPARED on a line by itself and expect it to read as a refusal."')])

rw('_part_main.sh', [(
    '"AUTHORIZATION ONLY. Do not run the product. Reply in the receipt with BOTH tokens: GO_AUTHORIZED and the nonce of THIS request, quoted exactly."',
    '"AUTHORIZATION ONLY. Do not run the product. Reply in the receipt with BOTH: the token GO_AUTHORIZED on a line of its own and nothing else on that line, and the nonce of THIS request quoted exactly (anywhere). To WITHHOLD authorization, say so in words -- there is no negative token this check reads."')])
