import io, hashlib, os, shutil

SP = r'C:\Users\decid\AppData\Local\Temp\claude\C--Users-decid-Documents-projects-spt-core\155d2e36-9d5d-48c8-8859-c4c1f9ac9e33\scratchpad'
os.makedirs(os.path.join(SP, 'frag-edited'), exist_ok=True)

# A. keep the EDITED header/cleanup safe before any reverse-apply
for f in ('_part1_header.sh', '_part_cleanup.sh'):
    shutil.copy2(f, os.path.join(SP, 'frag-edited', f))

# B. recover _part_main.sh from the assembled driver's tail
asm = io.open('fp-driver-d2.sh', encoding='utf-8', newline='').read()
marker = "  return 0\r\n}\r\n"
# the LAST retained block (d1_capture) ends with `return 0` + `}` + a blank line; _part_main
# follows it. Anchor on the unique d1_capture closing text.
uniq = "REPAIRED query (raw CIM accessor), so the const differs from 53d625cd by construction.\""
i = asm.index(uniq)
j = asm.index(marker, i) + len(marker)
# the assembler joins parts with '\r\n', so a single blank line separates the segments
assert asm[j:j + 2] == '\r\n', repr(asm[j:j + 8])
tail = asm[j + 2:]
assert tail.endswith('\r\n')
main = tail[:-2].replace('\r\n', '\n') + '\n'
io.open('_part_main.sh', 'w', encoding='utf-8', newline='').write(main)
print('recovered _part_main.sh bytes', len(main), 'first line:', main.split('\n')[0][:90])
