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. handoff_request lives in RETAINED text (keep(265,561)), so it is corrected the way this
#    assembler corrects retained text: in place, at assembly time, visible in the diff.
# ---------------------------------------------------------------------------
ASM_OLD = """note = ("# CONTEXT NAME KEPT VERBATIM: 'trial' is handoff_await's name for THE NORMAL FLOW, as\\r\\n"
        "# opposed to 'cleanup'. There are no trials here; renaming it would edit a function this\\r\\n"
        "# change has no reason to touch, so the name stays and this line says what it means.\\r\\n")"""

ASM_NEW = ASM_OLD + """

# A THIRD IN-PLACE CORRECTION (doyle XS5VAWJQ): handoff_request stamped EVERY request
# "elevation: REQUIRED", which addressed every request to the elevated EXECUTOR -- including the GO
# AUTHORIZATION, which is the DRI's decision and not the executor's. The function is retained text,
# so the audience becomes a 4th argument here rather than in a D2 fragment.
addr_old = ('    echo "elevation: REQUIRED \\u2014 the trial driver is unelevated by assertion (S0a) '
            'and will not run this itself"\\r\\n')
assert s.count(addr_old) == 1
addr_new = (
  '    # THE AUDIENCE IS PART OF THE REQUEST (doyle XS5VAWJQ). A request that says "elevation:\\r\\n'
  '    # REQUIRED" is addressed to the elevated executor. An AUTHORIZATION is not an action and is\\r\\n'
  '    # not the executor\\'s to give: readiness comes from whoever would run the leg, authorization\\r\\n'
  '    # comes from the DRI, and stamping both with the same header made them one channel.\\r\\n'
  '    case "${4:-executor}" in\\r\\n'
  '      doyle)\\r\\n'
  '        echo "audience: doyle (the DRI) \\u2014 THE ELEVATED EXECUTOR MUST NOT ANSWER THIS REQUEST"\\r\\n'
  '        echo "elevation: NOT_REQUIRED \\u2014 this is an authorization, not an action; nothing is run to answer it"\\r\\n'
  '        ;;\\r\\n'
  '      *)\\r\\n'
  '        echo "audience: the elevated executor"\\r\\n'
  '        echo "elevation: REQUIRED \\u2014 the trial driver is unelevated by assertion (S0a) and will not run this itself"\\r\\n'
  '        ;;\\r\\n'
  '    esac\\r\\n')
s = s.replace(addr_old, addr_new)"""

rw('rig-d2/assemble.sh', [(ASM_OLD, ASM_NEW)])

# ---------------------------------------------------------------------------
# 2. the GO request is addressed to doyle, and the receipt must name its authorizer
# ---------------------------------------------------------------------------
rw('_part_main.sh', [(
    """handoff_request go-authorization \\
  "AUTHORIZE ONLY -- RUN NOTHING. This is not a readiness question; you have already answered that. Authorize the experimental window to OPEN for this run, knowing the 300s activity clock starts when it does." \\
  "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.\"""",
    """handoff_request go-authorization \\
  "AUTHORIZE ONLY -- RUN NOTHING. FOR THE DRI, NOT FOR THE ELEVATED EXECUTOR: readiness has already been acknowledged by the leg that would run this, and that acknowledgment is not this decision. Authorize the experimental window to OPEN for this run, knowing the 300s activity clock starts when it does." \\
  "AUTHORIZATION ONLY. Nothing is run to answer this. Reply in the receipt with THREE things: the token GO_AUTHORIZED on a line of its own and nothing else on that line; the line authorizer=doyle, likewise alone on its 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." \\
  doyle""")])

rw('_part_main.sh', [(
    """ack_line "$GO_ACK" "GO_AUTHORIZED" || go_missing="$go_missing GO_AUTHORIZED\"""",
    """ack_line "$GO_ACK" "GO_AUTHORIZED" || go_missing="$go_missing GO_AUTHORIZED"
# THE AUTHORIZER IS NAMED, AND THAT IS A ROUTING CHECK, NOT AUTHENTICATION (doyle XS5VAWJQ).
# It establishes that the receipt answering this request claims to be the DRI's decision rather
# than the executor's; it cannot establish WHO wrote the file, and nothing here should be read as
# if it could. The operational authorization is doyle's own run-and-nonce-bound message; this
# receipt RECORDS that decision and does not create it.
ack_line "$GO_ACK" "authorizer=doyle" || go_missing="$go_missing authorizer=doyle\"""")])

rw('_part_main.sh', [(
    'record "GO_AUTHORIZED_VERIFIED nonce=$GO_ACK_NONCE - a separate, run-bound authorization, distinct from the readiness acknowledgment"',
    'record "GO_AUTHORIZED_VERIFIED nonce=$GO_ACK_NONCE authorizer=doyle - a separate, run-bound authorization from the DRI, distinct from the executor\'s readiness acknowledgment. The identity line is a routing and consistency check, not authentication: it records whose decision this receipt claims to carry."')])
