"""Extract frozen development crops from the checksum-verified UDE archive."""
import collections,csv,ctypes,hashlib,json,os,signal,time
from pathlib import Path
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')
 p=json.loads((O/'selection.json').read_text());assert not (O/'assets.json').exists() and p['ledger_sha256']==sha(R/'results/r112/ude-sampling-metadata/exposure-ledger.csv') and p['exposure_report_sha256']==sha(R/'results/r112/ude-sampling-metadata/exposure-report.json') and p['ude_metadata_sha256']==sha(M) and p['literal_name_guard_sha256']==sha(R/'diatom_pilot/ude_development_archive.py');ids={x['annotation_id'] for x in p['records']};assert len(ids)==len(p['records'])==4000;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;(O/'images').mkdir(exist_ok=True);records=[];start=time.monotonic()
 with UDEDevelopmentArchive() as dataset:
  for i,ref in enumerate(p['records']):
   v=dataset.read(ref['annotation_id'],require_plain_species=True);m=metadata[ref['annotation_id']];assert v['source_name']==ref['source_species']==m['species'] and v['source_genus']==ref['source_genus']==m['genus'] and v['source_slide']==ref['source_slide']==m['image_filename'] and v['site_component']==ref['site_component'] and v['exposure_status']=='prior_development' and v['source_annotation_shape']==m['shape'];name=ref['annotation_id']+'.png';target=O/'images'/name;temp=target.with_suffix('.png.tmp');v['image'].save(temp,format='PNG');temp.replace(target);w,h=v['image'].size;bbox=[int(m[k]) for k in ('bbox_x0','bbox_y0','bbox_x1','bbox_y1')];records.append({'annotation_id':ref['annotation_id'],'source_species':ref['source_species'],'source_genus':ref['source_genus'],'source_subspecies':m['subspecies'],'source_annotator':m['annotator'],'source_site_component':ref['site_component'],'source_slide_group':ref['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,'crop_vs_annotation_bbox_delta_px':[w-(bbox[2]-bbox[0]+1),h-(bbox[3]-bbox[1]+1)],'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)%25==0 or i+1==len(p['records']):
    temp=O/'progress.json.tmp';temp.write_text(json.dumps({'phase':'extracting_verified_archive','completed':i+1,'total':len(p['records']),'last_annotation_id':ref['annotation_id'],'elapsed_seconds':round(time.monotonic()-start,1),'note':'Last saved progress; not proof of process liveness.'},indent=2)+'\n');temp.replace(O/'progress.json')
   if (i+1)%250==0:print('extracted',i+1,'/',len(p['records']),'elapsed',round(time.monotonic()-start,1),flush=True)
 assert len(records)==4000 and all(x['source_crop'].endswith('.png') for x in records);out={'format':'r112-scaleup-assets-v1','selection_sha256':sha(O/'selection.json'),'archive_verification_sha256':sha(R/'results/r112/ude-sampling-metadata/archive-verification.json'),'script_sha256':sha(Path(__file__)),'source':'UDE DIATOMS in the Wild 2024, CC0; published source labels are not independently reconciled here.','warning':p['scope'],'records':records};(O/'assets.json').write_text(json.dumps(out,indent=2)+'\n');print('completed',len(records),'crops across',len({r['source_species'] for r in records}),'source-name strings',flush=True)
if __name__=='__main__':main()
