"""Post-hoc followup to frozen height-64 control; compare only I/l at fixed shape.
Usage: python transfer_ablation.py SOURCE_DIR GEOMETRY_JSON READER_A_JSON READER_B_JSON OUT_JSON
"""
from pathlib import Path
import json,sys
from collections import Counter
import numpy as np
from PIL import Image
from transfer_shapes import masked, readgeo, toint, score, variants
from transfer_labels import labels
def main():
    root,geo,A,B,out=map(Path,sys.argv[1:]);data=json.loads(geo.read_text());g=readgeo(geo);aa=labels(A);bb=labels(B)
    img={p:np.asarray(Image.open(root/f'{p+17}.jpg').convert('L')) for p in (49,50,51)}
    shapes={}
    for c,t,u in zip(data,aa,bb):
        if t in ('I','l'):
            assert t==u; m=g.masks(img[c['page']],c)[1]; h=masked(m);crop=h[2:-2,:]
            shapes[c['index']]=(c['page'],t,m,h,crop)
    res={}
    for op in (2,3,4):
        codes={}
        for i,q in shapes.items():
            m=q[op]; codes[i]=(toint(m),list(m.shape),int(m.sum()))
        rows=[]
        for i,q in shapes.items():
            v=codes[i][0];ds={}
            for j,r in shapes.items():
                if r[0]==q[0]:continue
                w=codes[j][0];pair=score(v,variants(v),v.bit_count(),w,variants(w),w.bit_count());d=pair[0]/pair[1]
                ds[r[1]]=min(d,ds.get(r[1],np.inf))
            rows.append(dict(index=i,gold=q[1],shape=codes[i][1],area=codes[i][2],nearest=[k for k,v in ds.items() if v==min(ds.values())],distances=ds))
        res[{2:'full_native',3:'height64',4:'height64_crop_two_rows_at_each_end'}[op]]=rows
    out.write_text(json.dumps(res,indent=1)+'\n'); print([[k,Counter(tuple(sorted(v['nearest'])) for v in ls)] for k,ls in res.items()])
if __name__=='__main__':main()
