"""Select clipped-control cases from reference geometry, before inference."""
import json
from pathlib import Path
import numpy as np
from l86_oracle import sha
R=Path(__file__).resolve().parents[1];O=R/'results/l91';p=json.loads((O/'protocol.json').read_text())
for f,h in p['inputs'].items():assert sha(R/f)==h
out=[]
for r in json.loads((R/'results/r106/results.json').read_text())['records']:
 z=np.load(R/'results/r106'/r['archive']);refs=z['refs'];assert sha(R/'results/r106'/r['archive'])==r['archive_sha256']
 if len(refs)!=1:continue
 ref=refs[0];yy,xx=np.nonzero(ref);x0,x1=int(xx.min()),int(xx.max());y0,y1=int(yy.min()),int(yy.max());shift=(x0+x1)//2;count=int((xx>=shift).sum());fraction=count/len(xx)
 if not (64<=shift<=240 and x0>4 and x1<507 and y0>68 and y1<443 and .3<=fraction<=.7 and count>=300):continue
 out.append({'id':r['id'],'source':r['source'],'source_sha256':r['source_sha256'],'r106_archive':r['archive'],'r106_archive_sha256':r['archive_sha256'],'used_for_r54_training':r['used_for_r54_training'],'original_bounds':[x0,y0,x1,y1],'shift':shift,'content_rect':[0,64,512-shift,448],'original_area':len(xx),'visible_area':count,'visible_fraction':fraction})
 if len(out)==8:break
assert len(out)==8;(O/'selection.json').write_text(json.dumps({'protocol_sha256':sha(O/'protocol.json'),'script_sha256':sha(__file__),'records':out},indent=2)+'\n');print('selected',len(out),'pre-existing viewed fields',[x['id'] for x in out])
