"""Extract exactly five indexed planes from each preselected complete scan."""
import hashlib,json,sys
from pathlib import Path
import numpy as np
ROOT=Path(__file__).resolve().parents[1];OUT=ROOT/'results/l46';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/'backgrounds.npz'
 if dest.exists():raise FileExistsError('Preserve extracted plane data')
 arrays={};records=[]
 for i,f in enumerate(s['backgrounds'],1):
  path=ROOT/'scans'/f['slide'];st=path.stat()
  if st.st_size<1_000_000_000 or st.st_size!=f['size_bytes'] or st.st_mtime_ns!=f['mtime_ns']:raise ValueError('Incomplete or changed source scan')
  with Stack(path) as stack:
   if stack.depth<5:raise ValueError('Insufficient source planes')
   x,y=f['origin_xy'];arr=np.stack([np.asarray(stack.field(z,x,y,768)) for z in f['plane_indices']]);arrays[f'field_{i}']=arr;info={'slide':f['slide'],'origin_xy':f['origin_xy'],'indices':f['plane_indices'],'source_xy_um':[stack.sx,stack.sy],'source_shape':[stack.width,stack.height,stack.depth],'crop_shape':list(arr.shape),'plane_sha256':[hashlib.sha256(a.tobytes()).hexdigest() for a in arr]}
  after=path.stat()
  if (st.st_size,st.st_mtime_ns)!=(after.st_size,after.st_mtime_ns):raise ValueError('Source scan changed while reading')
  records.append(info);print(f'{i}/3 stack fields extracted',flush=True)
 np.savez_compressed(dest,**arrays);(OUT/'backgrounds.json').write_text(json.dumps({'selection_sha256':sha(OUT/'selection.json'),'npz_sha256':sha(dest),'fields':records,'warning':'Previously inspected real backgrounds, no registration; local crop indices and approximate contrast are not object depth.'},indent=2)+'\n');print('Background extraction complete.',flush=True)
if __name__=='__main__':main()
