"""Freeze spatial/focal development background sampling before reading pixels."""
import csv,hashlib,json,random
from pathlib import Path
R=Path(__file__).resolve().parents[1];O=R/'results/r112/academy-backgrounds-v2';I=R/'results/scan-inventory.csv';B=R/'results/l78/training-selection.json';sha=lambda p:hashlib.sha256(p.read_bytes()).hexdigest()
def main():
 target=O/'protocol.json';assert not target.exists();inv={x['filename']:x for x in csv.DictReader(I.open())};old=json.loads(B.read_text())['backgrounds'];assert len(old)==8 and len({x['slide'] for x in old})==8;rng=random.Random(20261208);items=[]
 for b in old:
  meta=inv[b['slide']];scan=R/'scans'/b['slide'];size=scan.stat().st_size;assert size>=1_000_000_000 and size==b['slide_bytes']==int(meta['bytes']);w,h,z=map(int,(meta['width_px'],meta['height_px'],meta['z_planes']));assert z>=3 and min(w,h)>768;coords=[]
  while len(coords)<8:
   x=rng.randrange(0,w-768+1);y=rng.randrange(0,h-768+1)
   if abs(x-b['origin_xy'][0])<2048 and abs(y-b['origin_xy'][1])<2048:continue
   if any(abs(x-a)<2048 and abs(y-c)<2048 for a,c in coords):continue
   coords.append((x,y))
  for i,(x,y) in enumerate(coords):
   items.append({'slide':b['slide'],'slide_bytes':size,'site_index':i,'origin_xy':[x,y],'size_px':768,'z_indices':[z//2-1,z//2,z//2+1],'image_size_xy':[w,h],'plane_count':z,'um_per_pixel_xy':[float(meta['um_per_pixel_x']),float(meta['um_per_pixel_y'])]})
 protocol={'format':'r112-academy-backgrounds-v2','seed':20261208,'scan_inventory_sha256':sha(I),'existing_selection_sha256':sha(B),'selection':'Only the eight Academy slide filenames already used for R112 development backgrounds. Uniform pseudorandom 768-square locations, eight per slide; reject if within 2048 px in both axes of the previous background or another selected site on that slide. Retain the middle indexed plane and immediate neighbors. Selection fixed from metadata and prior coordinates before reading new pixels.','label_status':'All pixels and structures unknown, including potential diatoms and fragments. These are development backgrounds, not known empty or annotated negatives.','limits':'Filename slides are not proven independent biological samples. Chosen locations are nonrepresentative, focal plane indices are not measured Z distances, TIFF optical/acquisition variation not corrected; no specimen-quality or overlap labels. Additional Academy slides are not used by this selection. Scans below 1,000,000,000 bytes are never read.','fields':items};target.write_text(json.dumps(protocol,indent=2)+'\n');print('Frozen',len(items),'positions;',3*len(items),'planes on',len(old),'previously used development slides')
if __name__=='__main__':main()
