"""Verify every extracted source crop against the guarded UDE archive and metadata."""
import collections,csv,ctypes,hashlib,json,os,signal
from pathlib import Path
import numpy as np
from PIL import Image
from diatom_pilot.ude_development_archive import UDEDevelopmentArchive
R=Path(__file__).resolve().parents[1];O=R/'results/r112/species-scaleup';M=Path('/tmp/ude-metadata.csv');sha=lambda p:hashlib.sha256(Path(p).read_bytes()).hexdigest()
def main():
 parent=os.getppid();assert ctypes.CDLL(None,use_errno=True).prctl(1,signal.SIGTERM)==0
 if parent!=os.getppid():raise RuntimeError('launcher exited')
 selection=json.loads((O/'selection.json').read_text());assets=json.loads((O/'assets.json').read_text());assert assets['selection_sha256']==sha(O/'selection.json') and assets['script_sha256']==sha(R/'research/r112_scaleup_extract.py') and assets['archive_verification_sha256']==sha(R/'results/r112/ude-sampling-metadata/archive-verification.json') and selection['ude_metadata_sha256']==sha(M);assert len(selection['records'])==len(assets['records'])==4000;ids={r['annotation_id'] for r in selection['records']};metadata={}
 with M.open(encoding='utf-8-sig',newline='') as f:
  for r in csv.DictReader(f):
   if r['annotation_id'] in ids:metadata[r['annotation_id']]=r
 assert set(metadata)==ids;by_species=collections.defaultdict(list)
 with UDEDevelopmentArchive() as archive:
  for i,(a,b) in enumerate(zip(selection['records'],assets['records'])):
   ident=a['annotation_id'];m=metadata[ident];v=archive.read(ident,require_plain_species=True);p=O/b['source_crop'];assert ident==b['annotation_id'] and a['source_species']==b['source_species']==m['species']==v['source_name'] and a['source_genus']==b['source_genus']==m['genus']==v['source_genus'] and a['site_component']==b['source_site_component']==v['site_component'] and a['source_slide']==b['source_slide_group']==m['image_filename'] and v['exposure_status']=='prior_development';assert sha(p)==b['source_sha256'] and v['archive_member_sha256']==b['archive_member_sha256'] and v['archive_member_crc32']==b['archive_member_crc32'] and np.array_equal(np.asarray(Image.open(p).convert('L')),np.asarray(v['image']));assert b['source_annotation_shape']==m['shape'] and b['source_annotation_points_global']==json.loads(m['points']) and b['source_annotation_bbox_global']==[int(m[k]) for k in ('bbox_x0','bbox_y0','bbox_x1','bbox_y1')] and b['source_dimensions_px']==list(v['image'].size);by_species[a['source_species']].append(a)
   if (i+1)%500==0:print('verified',i+1,'/',len(assets['records']),flush=True)
 assert len(by_species)==80
 for name,items in by_species.items():
  assert len(items)==50 and len({x['site_component'] for x in items})>=5 and max(collections.Counter(x['site_component'] for x in items).values())<=10 and max(collections.Counter(x['source_slide'] for x in items).values())<=3
 out={'format':'r112-scaleup-verify-v1','selection_sha256':sha(O/'selection.json'),'assets_sha256':sha(O/'assets.json'),'script_sha256':sha(Path(__file__)),'crops':len(ids),'source_name_strings':len(by_species),'checks':'Every development status, archive member SHA/CRC, re-encoded grayscale pixels, selected metadata, class count, site cap and slide cap checked through guarded archive reader. Does not validate specimen identity, exact biological independence, instance masks, optical match or model performance.'};(O/'verify.json').write_text(json.dumps(out,indent=2)+'\n');print(json.dumps(out,indent=2),flush=True)
if __name__=='__main__':main()
