# usage: applyspells.py <in spells_us.txt> <lines file> <out>  (replace same id, insert new ids in id order; keeps EOL style)
import sys
src,lf,dst=sys.argv[1:4]
data=open(src,'rb').read()
nl=b'\r\n' if b'\r\n' in data[:100000] else b'\n'
trail=data.endswith(nl)
L=data.split(nl)
if trail: L=L[:-1]
new={}
for l in open(lf,'rb').read().split(b'\n'):
    l=l.rstrip(b'\r')
    if l.strip(): new[int(l.split(b'^',1)[0])]=l
ids=[int(x.split(b'^',1)[0]) for x in L]
pos={v:i for i,v in enumerate(ids)}
rep=ins=0
for k,l in new.items():
    if k in pos and L[pos[k]]!=l: L[pos[k]]=l; rep+=1
for k in sorted(new):
    if k in pos: continue
    i=next((j for j,v in enumerate(ids) if v>k),len(L))
    L.insert(i,new[k]); ids.insert(i,k); ins+=1
open(dst,'wb').write(nl.join(L)+(nl if trail else b''))
print(f"replaced {rep}, inserted {ins}")
