"""Re-read every eligible archive image and verify extracted grayscale pixels."""
import collections,csv,json
from pathlib import Path
import numpy as np
from PIL import Image
from diatom_pilot.ude_development_archive import UDEDevelopmentArchive
from r112_scaleup_synthetic_compare import sha
R=Path(__file__).resolve().parents[1];O=R/'results/r112/species-breadth';selection=json.loads((O/'selection.json').read_text());sv=json.loads((O/'selection-verify.json').read_text());assets=json.loads((O/'assets.json').read_text());assert assets['selection_sha256']==sv['selection_sha256']==sha(O/'selection.json');assert assets['script_sha256']==sha(R/'research/r112_species_breadth_extract.py') and assets['archive_verification_sha256']==sha(R/'results/r112/ude-sampling-metadata/archive-verification.json');assert len(assets['records'])==len(selection['records'])==1096;names=collections.Counter();genera=set();sizes=[]
with UDEDevelopmentArchive() as archive:
 for i,(r,a) in enumerate(zip(selection['records'],assets['records'])):
  assert r['annotation_id']==a['annotation_id'] and r['source_species']==a['source_species'];v=archive.read(a['annotation_id'],require_plain_species=True);path=O/a['source_crop'];assert path.resolve()==(O/'images'/f"{a['annotation_id']}.png").resolve() and sha(path)==a['source_sha256'] and v['archive_member_sha256']==a['archive_member_sha256'] and v['archive_member_crc32']==a['archive_member_crc32'];img=np.asarray(Image.open(path));assert img.ndim==2 and img.dtype==np.uint8 and np.array_equal(img,np.asarray(v['image'])) and [img.shape[1],img.shape[0]]==a['source_dimensions_px'];assert (v['source_name'],v['source_genus'],v['site_component'],v['source_slide'],v['source_annotation_shape'])==(a['source_species'],a['source_genus'],a['source_site_component'],a['source_slide_group'],a['source_annotation_shape']);names[a['source_species']]+=1;genera.add(a['source_genus']);sizes.append(img.size)
  if (i+1)%200==0:print('verified',i+1,'/',len(assets['records']),flush=True)
assert len(names)==137 and set(names.values())=={8} and len(genera)==55
report={'format':'r112-species-breadth-verify-v1','assets_sha256':sha(O/'assets.json'),'selection_sha256':sha(O/'selection.json'),'archive_verification_sha256':assets['archive_verification_sha256'],'crops':len(sizes),'source_name_strings':len(names),'source_genera':len(genera),'checks':'Every extracted grayscale crop was reread from the checksum-verified UDE archive using the guarded prior-development reader; file and archive-member hashes, CRC, exact pixels, dimensions, source name, genus, site group, slide, and annotation shape checked. This does not validate scientific names, sample independence, masks or background labels.'};(O/'verify.json').write_text(json.dumps(report,indent=2)+'\n');print(json.dumps(report,indent=2))
