import sys
old_file = sys.argv[1]
new_file = sys.argv[2]
target   = sys.argv[3]

with open(old_file, 'rb') as f:
    old = f.read().decode('utf-8').replace('\r\n', '\n').replace('\r', '\n')
with open(new_file, 'rb') as f:
    new = f.read().decode('utf-8').replace('\r\n', '\n').replace('\r', '\n')
with open(target, 'rb') as f:
    raw = f.read()
# detect line ending in target
crlf = b'\r\n' in raw
doc = raw.decode('utf-8').replace('\r\n', '\n').replace('\r', '\n')

if old not in doc:
    print('ERROR: old_string not found in', target)
    # show closest match
    words = old[:30]
    idx = doc.find(words[:20])
    print('Closest at:', idx, repr(doc[idx:idx+60]) if idx >= 0 else 'not found')
    sys.exit(1)

doc2 = doc.replace(old, new, 1)
if crlf:
    doc2 = doc2.replace('\n', '\r\n')
with open(target, 'wb') as f:
    f.write(doc2.encode('utf-8'))
print('OK replaced 1 occurrence in', target)
