"""Extract frozen local stack crops without reading partial scans."""
import hashlib,json,sys
from pathlib import Path
import numpy as np
ROOT=Path(__file__).resolve().parents[1];OUT=ROOT/'results/r59';sys.path.insert(0,str(ROOT/'experiments'))
from scan_fields import Stack
def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()
def main():
 s=json.loads((OUT/'selection.json').read_text());dest=OUT/'crops.npz'
 if dest.exists():raise FileExistsError('Preserve existing crops')
 arrays={};records=[]
 for i,r in enumerate(s['selection'],1):
  path=ROOT/'scans'/r['slide'];st=path.stat()
  if st.st_size<1_000_000_000 or (st.st_size,st.st_mtime_ns)!=(r['size_bytes'],r['mtime_ns']):raise ValueError('Incomplete or changed scan')
  with Stack(path) as stack:
   if stack.depth<=max(r['plane_indices']):raise ValueError('Insufficient planes')
   x,y=r['origin_xy'];a=np.stack([np.asarray(stack.field(z,x,y,768)) for z in r['plane_indices']]);arrays[f'field_{i}']=a;records.append({'slide':r['slide'],'split':r['split'],'origin_xy':r['origin_xy'],'indices':r['plane_indices'],'source_xy_um':[stack.sx,stack.sy],'source_shape':[stack.width,stack.height,stack.depth],'plane_sha256':[hashlib.sha256(x.tobytes()).hexdigest() for x in a]})
  after=path.stat()
  if (st.st_size,st.st_mtime_ns)!=(after.st_size,after.st_mtime_ns):raise ValueError('Scan changed while reading')
  print(f'{i}/6 crops extracted',flush=True)
 np.savez_compressed(dest,**arrays);(OUT/'crops.json').write_text(json.dumps({'selection_sha256':sha(OUT/'selection.json'),'npz_sha256':sha(dest),'fields':records,'warning':'Native crops from distinct file names; sample independence and real plane alignment unverified.'},indent=2)+'\n');print('Crop extraction complete.',flush=True)
if __name__=='__main__':main()
