"""Freeze eligible edge-contact candidates and prompts before contextual inference."""
import hashlib,json
from pathlib import Path
import numpy as np
R=Path(__file__).resolve().parents[1];O=R/'results/r111';prior=R/'results/r110'
def sha(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest()
p=json.loads((prior/'protocol.json').read_text());r=json.loads((prior/'results.json').read_text());fields=[]
for f,row in zip(p['fields'],r['records']):
 assert sha(prior/row['archive'])==row['archive_sha256'];z=np.load(prior/row['archive']);shape=tuple(z['tile_shape']);m=np.unpackbits(z['tile_bits'])[:np.prod(shape)].reshape(shape).astype(bool);lookup={v:i for i,v in enumerate(z['tile_ids'].tolist())};cases=[]
 for rank,ident in enumerate(row['tile_ranking'][:10],1):
  i=lookup[ident];mask=m[i];x0,y0,x1,y1=map(int,z['tile_crops'][i]);sides=[]
  if x0>0 and mask[y0:y1,x0].any():sides.append('left')
  if x1<512 and mask[y0:y1,x1-1].any():sides.append('right')
  if y0>0 and mask[y0,x0:x1].any():sides.append('top')
  if y1<512 and mask[y1-1,x0:x1].any():sides.append('bottom')
  if not sides:continue
  ys,xs=np.where(mask);bx0,bx1=int(xs.min()),int(xs.max()+1);by0,by1=int(ys.min()),int(ys.max()+1);mx=max(16,int(np.ceil((bx1-bx0)*.25)));my=max(16,int(np.ceil((by1-by0)*.25)));box=[max(0,bx0-mx),max(0,by0-my),min(511,bx1+mx),min(511,by1+my)]
  cases.append({'id':ident,'rank':rank,'raw_index':i,'point':z['tile_points'][i].tolist(),'crop':[x0,y0,x1,y1],'contact_sides':sides,'expanded_box':box,'original_area':int(mask.sum())})
 fields.append({'index':f['index'],'image':f['middle_image'],'image_sha256':f['middle_sha256'],'archive':row['archive'],'archive_sha256':row['archive_sha256'],'cases':cases})
protocol={'format':'r111-context-v1','r110_results_sha256':sha(prior/'results.json'),'r110_protocol_sha256':sha(prior/'protocol.json'),'checkpoint_sha256':p['sam_sha256'],'selector_sha256':sha(__file__),'selection':'All R110 top-10 tiled candidates that touch any internal tile edge, fixed from saved masks without biological annotations. One case per retained candidate, including duplicates/ambiguous or debris candidates; exclude outer field edges because missing context cannot be recovered.','inputs':'Original grayscale middle-plane Academy crops from R110; 512 native pixels. Previously examined development fields.','prompts':'Single original tile variance point, and separately a bounding box enclosing the original candidate expanded on each side by 25% of mask extent with minimum 16 pixels and clipped to the 512 field. Both queried on the entire image. One image encoding per field.','evaluation':'For each contacted edge, count newly occupied pixels outside the crop on that side; report any extension, original-mask retained fraction, new/original area, and score. No filtering or NMS. Keep original and both generated alternatives. Equal-budget first ten view retains first ten original tiled candidates; per-candidate galleries compare alternatives, no claim of improved segmentation or accuracy.','fields':fields}
(O/'protocol.json').write_text(json.dumps(protocol,indent=2)+'\n');print('cases per field:',[len(x['cases']) for x in fields])
