"""python edit_cost_362.py EVIDENCE OUT.json; construct minimum replacements for best and preferred readings."""
from pathlib import Path
from collections import Counter
import json,sys,gzip
from digest_359 import A,demand,consume
def main(d,o):
 cells=json.loads((d/'grid_cells_254.json').read_bytes())['cells'];ts=[c['b'] for c in cells]
 res=json.loads(gzip.decompress((d/'digest_359_results.json.gz').read_bytes()));t=bytes.fromhex(res['target_hex']);b=A.replace('f','');best=res['best'];assert best[:3]==[23,'compact59',0]
 out={}
 for name,alpha,base in [('conventional',A,60),('best_example',b,59)]:
  tape=bytes(base*alpha.index(w[0])+alpha.index(w[1]) for w in ts);need=Counter(t);spare=[];remaining=need.copy()
  for i,v in enumerate(tape):
   if remaining[v]>0:remaining[v]-=1
   else:spare.append(i)
  missing=sorted(remaining.elements());y=bytearray(tape);ed=[]
  for i,v in zip(spare,missing):ed.append([i,tape[i],v]);y[i]=v
  assert len(spare)>=len(missing) and len(ed)==len(consume(tape,t)) and not consume(y,t)
  take=[];used=set()
  for v in t:
   i=next(i for i,n in enumerate(y) if n==v and i not in used);used.add(i);take.append(i)
  assert bytes(y[i] for i in take)==t and len(set(take))==64
  out[name]={'minimum_changed_cells':len(ed),'illustrative_not_manuscript_edits_zero_based':ed,'illustrative_64_distinct_source_indices_after_edits':take}
 o.write_text(json.dumps(out,indent=2,sort_keys=True)+'\n')
if __name__=='__main__':main(*map(Path,sys.argv[1:]))
