"""Extract a frozen breadth selection through the guarded, verified UDE archive."""
import csv,ctypes,json,os,signal,time
from pathlib import Path
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';M=Path('/tmp/ude-metadata.csv')
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')
 p=json.loads((O/'selection.json').read_text());assert not (O/'assets.json').exists() and p['metadata_sha256']==sha(M)
 for f,h in p['inputs_sha256'].items():assert sha(R/f)==h,f
 ids={x['annotation_id'] for x in p['records']};assert len(ids)==1096;meta={}
 with M.open(encoding='utf-8-sig',newline='') as f:
  for r in csv.DictReader(f):
   if r['annotation_id'] in ids:meta[r['annotation_id']]=r
 assert set(meta)==ids;(O/'images').mkdir(exist_ok=True);rows=[];start=time.monotonic()
 with UDEDevelopmentArchive() as archive:
  for i,r in enumerate(p['records']):
   v=archive.read(r['annotation_id'],require_plain_species=True);m=meta[r['annotation_id']];assert v['source_name']==r['source_species']==m['species'] and v['source_genus']==r['source_genus']==m['genus'] and v['source_slide']==r['source_slide']==m['image_filename'] and v['site_component']==r['site_component'] and v['source_annotation_shape']==m['shape'] and v['exposure_status']=='prior_development';name=r['annotation_id']+'.png';target=O/'images'/name;tmp=target.with_suffix('.png.tmp');v['image'].save(tmp,format='PNG');tmp.replace(target);w,h=v['image'].size;bbox=[int(m[k]) for k in ('bbox_x0','bbox_y0','bbox_x1','bbox_y1')];rows.append({'annotation_id':r['annotation_id'],'source_species':r['source_species'],'source_genus':r['source_genus'],'source_subspecies':m['subspecies'],'source_annotator':m['annotator'],'source_site_component':r['site_component'],'source_slide_group':r['source_slide'],'source_crop':f'images/{name}','source_sha256':sha(target),'archive_member_sha256':v['archive_member_sha256'],'archive_member_crc32':v['archive_member_crc32'],'source_dimensions_px':[w,h],'source_annotation_shape':m['shape'],'source_annotation_points_global':json.loads(m['points']),'source_annotation_bbox_global':bbox,'source_scale_um_px':[.09,.09],'taxonomic_status':'UDE source name; not independently reconciled','mask_status':'no verified instance mask','source_sample_independence':'unknown','background_status':'unknown; crop may contain other organisms'})
   if (i+1)%100==0:print('extracted',i+1,'/',len(ids),'seconds',round(time.monotonic()-start),flush=True)
 result={'format':'r112-species-breadth-assets-v1','selection_sha256':sha(O/'selection.json'),'archive_verification_sha256':sha(R/'results/r112/ude-sampling-metadata/archive-verification.json'),'script_sha256':sha(__file__),'source':'UDE Diatoms in the Wild 2024, CC0; authors reviewed labels, which are not independently reconciled here.','warning':p['warning'],'records':rows};(O/'assets.json').write_text(json.dumps(result,indent=2)+'\n');print('complete',len(rows),'source crops',flush=True)
if __name__=='__main__':main()
