import io
import importlib.util

# Reuse the edit texts from edit2.py WITHOUT executing it: load the source and split out the
# literals. edit2.py is the file whose own bug truncated _part_main.sh; nothing in it runs here.
src = io.open(r'C:\Users\decid\AppData\Local\Temp\claude\C--Users-decid-Documents-projects-spt-core\155d2e36-9d5d-48c8-8859-c4c1f9ac9e33\scratchpad\edit2.py',
              encoding='utf-8', newline='').read()


def lit(name):
    body = src.split(name + ' = """')[1].split('"""')[0]
    # a literal ending in an escaped quote (\") is cut by the naive split: restore it
    if body.endswith(chr(92)):
        body = body[:-1] + '"'
    # the literals were written with a trailing \" escape for a closing bash quote
    return body.replace('\\"', '"').replace('\\\\', '\\')


MAIN_OLD, MAIN_NEW = lit('MAIN_OLD'), lit('MAIN_NEW')
CL_OLD, CL_NEW = lit('CL_OLD'), lit('CL_NEW')
POST_OLD, POST_NEW = lit('POST_OLD'), lit('POST_NEW')


def rw(path, pairs):
    s = io.open(path, 'r', encoding='utf-8', newline='').read()
    nl = '\r\n' if '\r\n' in s else '\n'
    out = s
    for old, new in pairs:
        o = old.replace('\n', nl)
        assert o in out, 'anchor missing in %s: %r' % (path, old[:60])
        out = out.replace(o, new.replace('\n', nl), 1)
    # COMPUTED BEFORE THE FILE IS OPENED FOR WRITE. Opening 'w' truncates, so a failure after
    # that point destroys the source -- which is exactly how _part_main.sh was lost once.
    assert out != s
    io.open(path, 'w', encoding='utf-8', newline='').write(out)
    print('patched', path)


rw('_part_main.sh', [(MAIN_OLD, MAIN_NEW)])
rw('_part_cleanup.sh', [(CL_OLD, CL_NEW), (POST_OLD, POST_NEW)])
