import hashlib, json, os, sys
HERE=os.path.dirname(os.path.abspath(__file__))
P="/home/openclaw/heroes_journey_workspace/patcher/"; SRC=P+"staged_sympathetic/"; DST=P+"staged_fabled_epics/"
os.makedirs(DST+"tools", exist_ok=True)
sp=open(SRC+"spells_us.txt","rb").read(); db=open(SRC+"dbstr_us.txt","rb").read()
MS, MD = hashlib.md5(sp).hexdigest(), hashlib.md5(db).hexdigest()
# usage: stage.py [base_dir]  (default staged_sympathetic; for a rebuild pass patcher/patch_files and update publish.sh md5s)
if len(sys.argv)>1: SRC=sys.argv[1].rstrip("/")+"/"; sp=open(SRC+"spells_us.txt","rb").read(); db=open(SRC+"dbstr_us.txt","rb").read(); MS, MD = hashlib.md5(sp).hexdigest(), hashlib.md5(db).hexdigest()
else: assert MS=="b75f0646f3b9a4fb2314c5d5a18f644a" and MD=="ac8c55c5cb64044d468b6c597392cdbe", (MS, MD)
assert b"\r" not in sp[:100000] and not sp.endswith(b"\n") and not db.endswith(b"\n")
spl=sp.split(b"\n"); dbl=db.split(b"\n")
new=[l.rstrip("\n").encode() for l in open(os.path.join(HERE,"spells_rows.txt"))]
newd=[l.rstrip("\n").encode() for l in open(os.path.join(HERE,"dbstr_rows.txt"))]
ids=[int(l.split(b"^",1)[0]) for l in spl]; have=set(ids)
nids=[int(l.split(b"^",1)[0]) for l in new]
assert not (set(nids) & have) and nids==sorted(nids)
nf=len(spl[ids.index(6264)].split(b"^"))
assert all(len(l.split(b"^"))==nf for l in new)
pos=next(i for i,x in enumerate(ids) if x>nids[-1])
assert ids[pos-1] < nids[0]
out=spl[:pos]+new+spl[pos:]
d6=set(int(l.split(b"^")[0]) for l in dbl if l.split(b"^")[1:2]==[b"6"])
assert not (set(int(l.split(b"^")[0]) for l in newd) & d6)
dout=dbl+newd
for l in new+newd: assert b"%" not in l
open(DST+"spells_us.txt","wb").write(b"\n".join(out)); open(DST+"dbstr_us.txt","wb").write(b"\n".join(dout))
# verify: only insertions
o=open(DST+"spells_us.txt","rb").read().split(b"\n"); assert [l for l in o if int(l.split(b"^",1)[0]) not in set(nids)]==spl
assert open(DST+"dbstr_us.txt","rb").read().split(b"\n")[:len(dbl)]==dbl
summ={"built_on":"staged_sympathetic (the files the 2026-10-26 08:15 UTC patcher update publishes)",
      "base_md5":{"spells_us.txt":MS,"dbstr_us.txt":MD},
      "new_md5":{"spells_us.txt":hashlib.md5(b"\n".join(out)).hexdigest(),"dbstr_us.txt":hashlib.md5(b"\n".join(dout)).hexdigest()},
      "spells_us_rows_inserted":len(new),"spell_ids":[nids[0],nids[-1]],"inserted_after_spell_id":ids[pos-1],
      "dbstr_type6_lines_appended":len(newd),"other_lines_changed":0,
      "spells":json.load(open(os.path.join(HERE,"summary.json")))["spells"]}
json.dump(summ, open(DST+"diff_summary.json","w"), indent=1)
print(json.dumps({k:v for k,v in summ.items() if k!="spells"}, indent=1))
