"""Verify and extract bounded focal crops from a public NDPI example."""
import hashlib,json,time
from pathlib import Path
import numpy as np,tifffile,imagecodecs,zarr
from PIL import Image,ImageDraw
from diatom_pilot.ndpi_crop import crop_ndpi
ROOT=Path(__file__).resolve().parents[1];OUT=ROOT/'results/r65';SCAN=Path('/tmp/diatom-r65-public-scan.ndpi')
def sha(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest()
def main():
 sel=json.loads((OUT/'selection.json').read_text());p=json.loads((OUT/'protocol.json').read_text());source=sel['file']
 if sha(OUT/'selection.json')!=p['selection_sha256'] or sha(ROOT/'diatom_pilot/ndpi_crop.py')!=p['crop_script_sha256'] or SCAN.stat().st_size!=source['size'] or sha(SCAN)!=p['scan_sha256']:raise ValueError('Frozen inputs changed or scan incomplete')
 if (OUT/'results.json').exists():raise FileExistsError('Preserve existing result')
 t=time.monotonic();crops={c['name']:crop_ndpi(SCAN,c['x'],c['y'],c['width'],c['height']) for c in p['crops']};edge=crop_ndpi(SCAN,3560,137,128,64);comparisons=[]
 with tifffile.TiffFile(SCAN) as tf:
  page=[pg for pg in tf.pages if pg.shape==(15360,17920,3)];zvals=[int(pg.tags[65424].value) for pg in page];assert zvals==p['full_resolution_plane_z_tags'];series=tf.series[0];levels=[{'shape':list(l.shape),'axes':l.axes} for l in series.levels];tiny=series.levels[-1].asarray();resolution=[list(page[0].tags[n].value) for n in ('XResolution','YResolution')];unit=int(page[0].tags['ResolutionUnit'].value)
  for z,pg in enumerate(page):
   full=pg.asarray()
   for c in p['crops']:
    eq=bool(np.array_equal(crops[c['name']][z],full[c['y']:c['y']+c['height'],c['x']:c['x']+c['width']]));comparisons.append({'plane':z,'crop':c['name'],'matches_full_plane':eq})
    if not eq:raise AssertionError('Bounded crop differs from full-page decode')
   eq=bool(np.array_equal(edge[z],full[137:201,3560:3688]));comparisons.append({'plane':z,'crop':'tile_boundary_test','matches_full_plane':eq})
   if not eq:raise AssertionError('Tile-boundary crop differs from full-page decode')
   del full
 np.savez_compressed(OUT/'native-crops.npz',**crops)
 cards=[]
 for c in p['crops']:
  frames=crops[c['name']];canvas=Image.new('RGB',(5*512,548),'white');d=ImageDraw.Draw(canvas)
  for i,im in enumerate(frames):canvas.paste(Image.fromarray(im),(i*512,36));d.text((i*512+8,8),f'Plane {i} · tag {zvals[i]}',fill='#203a38')
  file=c['name']+'-planes.jpg';canvas.save(OUT/file,quality=90);cards.append({**c,'plane_sha256':[hashlib.sha256(im.tobytes()).hexdigest() for im in frames],'image':file,'image_sha256':sha(OUT/file)})
 overview=Image.fromarray(tiny[2]);overview.save(OUT/'overview.jpg',quality=88)
 result={'format':'r65-ndpi-crops-v1','protocol_sha256':sha(OUT/'protocol.json'),'source_file':source,'tifffile_version':tifffile.__version__,'imagecodecs_version':imagecodecs.__version__,'zarr_version':zarr.__version__,'axes':'ZYXS','series_shape':list(series.shape),'levels':levels,'full_resolution_z_tags':zvals,'z_tag_unit':'not confirmed from authoritative format documentation','x_y_resolution_tiff':resolution,'resolution_unit':unit,'implied_um_per_pixel_x':10000*resolution[0][1]/resolution[0][0] if unit==3 else None,'published_paper_um_per_pixel':0.23,'crops':cards,'crops_sha256':sha(OUT/'native-crops.npz'),'overview_sha256':sha(OUT/'overview.jpg'),'verification':comparisons,'runtime_seconds':round(time.monotonic()-t,3),'warning':'Public marine fossil source, not freshwater. Geometry-selected fields and no per-instance masks; z tags recorded without assumed unit. TIFF-resolution-derived scale differs from rounded paper value; calibrate before morphometrics. Overview includes only image pixels, no scan-label macro.'};(OUT/'results.json').write_text(json.dumps(result,indent=2)+'\n');print('Extracted 3 crops, verified',len(comparisons),'full-plane comparisons; scan',source['filename'],flush=True)
if __name__=='__main__':main()
