"""Freeze four-edge controlled clips using source reference geometry."""
import json
from pathlib import Path
import numpy as np
from l86_oracle import sha
R=Path(__file__).resolve().parents[1];O=R/'results/r108';p=json.loads((O/'protocol.json').read_text())
for f,h in p['inputs'].items():assert sha(R/f)==h
rows=json.loads((R/'results/r105/results.json').read_text())['records'];screen={x['index']:x for x in json.loads((R/'results/r98/source-screen.json').read_text())['records']};prior={x['id'] for x in json.loads((R/'results/l91/selection.json').read_text())['records']};selected=[];used=set()
for target_fraction in (.35,.65):
 for side in ('left','right','top','bottom'):
  choice=None
  for row in rows:
   if row['index'] in used:continue
   s=screen[row['index']];assert not s['quarantined'] and s['source_image_sha256']==row['source_sha256'];assert not any(x['flag'] and x['reference_group']=='r80' and str(x['reference_name']) in prior for x in s['comparisons']);z=np.load(R/'results/r105'/row['archive']);assert sha(R/'results/r105'/row['archive'])==row['archive_sha256'];refs=z['refs'];ids=z['ids'].tolist()
   for i,ref in enumerate(refs):
    yy,xx=np.nonzero(ref);area=len(xx)
    if area<300:continue
    coords=xx if side in ('left','right') else yy;opts=[]
    for c in np.unique(coords):
     c=int(c)
     if side=='left':remaining=512-c;mask=coords>=c
     elif side=='right':remaining=c+1;mask=coords<=c
     elif side=='top':remaining=448-c;mask=coords>=c
     else:remaining=c-64+1;mask=coords<=c
     kept=int(mask.sum());frac=kept/area
     if remaining>=128 and kept>=100 and .2<=frac<=.8:opts.append((abs(frac-target_fraction),c,kept,frac))
    if opts:
     _,cut,kept,frac=min(opts);choice={'index':row['index'],'source':row['source'],'source_sha256':row['source_sha256'],'r105_archive':row['archive'],'r105_archive_sha256':row['archive_sha256'],'ref_index':i,'annotation_id':ids[i],'side':side,'target_fraction':target_fraction,'cut':cut,'source_area':area,'visible_area':kept,'visible_fraction':frac};break
   if choice:break
  assert choice is not None,(side,target_fraction);selected.append(choice);used.add(choice['index'])
assert len(selected)==8;(O/'selection.json').write_text(json.dumps({'protocol_sha256':sha(O/'protocol.json'),'script_sha256':sha(__file__),'records':selected},indent=2)+'\n');print([(v['index'],v['side'],round(v['visible_fraction'],3)) for v in selected])
