"""Preserve original-resolution source crops and provisional individual supports."""
import collections,ctypes,hashlib,json,os,signal
from pathlib import Path
import cv2,numpy as np
from PIL import Image,ImageDraw
R=Path(__file__).resolve().parents[1];O=R/'results/r112/design/native-assets';M=R/'results/r112/design/broader/manifest.json'
def sha(p):return 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')
 cv2.setNumThreads(2);p=json.loads(M.read_text());sources={}
 for row in p['scenes']:
  for x in row['instances']:
   s=x['source'];key=(s['image_sha256'],s.get('annotation_id',s.get('component_label')));sources[key]=s
 O.mkdir(parents=True,exist_ok=True)
 if (O/'manifest.json').exists():raise FileExistsError('Existing native assets; choose a new destination')
 rows=[];cache={}
 for i,(key,s) in enumerate(sorted(sources.items(),key=lambda x:str(x[0]))):
  ip=R/s['image_path'];assert sha(ip)==s['image_sha256'];image=np.asarray(Image.open(ip).convert('RGB'))
  if 'mask_path' in s:
   mp=R/s['mask_path'];xp=R/s['xml_path'];assert sha(mp)==s['mask_sha256'] and sha(xp)==s['xml_sha256'];cachekey=s['mask_sha256']
   if cachekey not in cache:
    binary=np.asarray(Image.open(mp).convert('L'))>0;_,cache[cachekey]=cv2.connectedComponents(binary.astype('uint8'),connectivity=8)
   mask=cache[cachekey]==s['component_label']
  else:
   ap=R/s['annotation_path'];assert sha(ap)==s['annotation_sha256'];data=json.loads(ap.read_text());ann=next(a for a in data['annotations'] if a['id']==s['annotation_id'] and a['image_id']==s['image_id']);mask=np.zeros(image.shape[:2],np.uint8)
   for poly in ann['segmentation']:cv2.fillPoly(mask,[np.rint(np.asarray(poly).reshape(-1,2)).astype('int32')],1
   )
   mask=mask.astype(bool)
  assert image.shape[:2]==mask.shape;yy,xx=np.where(mask);assert len(xx)>0;x0,x1=int(xx.min()),int(xx.max()+1);y0,y1=int(yy.min()),int(yy.max()+1);image_name=f'asset-{i:03d}-image.png';mask_name=f'asset-{i:03d}-mask.png';Image.fromarray(image[y0:y1,x0:x1]).save(O/image_name);Image.fromarray(mask[y0:y1,x0:x1].astype('uint8')*255).save(O/mask_name);rows.append({'id':f'asset-{i:03d}','source':s,'source_crop_xyxy':[x0,y0,x1,y1],'native_crop_size':[x1-x0,y1-y0],'source_image_crop':image_name,'source_image_crop_sha256':sha(O/image_name),'source_support_mask':mask_name,'source_support_mask_sha256':sha(O/mask_name),'physical_scale_um_per_pixel':None,'taxonomic_validation':'source label only; no expert confirmation','eligible_for_independent_test':False})
 out={'format':'r112-native-assets-v1','source_manifest_sha256':sha(M),'generator_sha256':sha(__file__),'purpose':'Development-only, unresized source crops and candidate masks for future rendering; not independent reference labels or a species classifier.','license_warning':'Gündüz inputs and derivatives CC BY-NC-SA 4.0; Khanom inputs CC BY 4.0; check provenance and downstream terms.','warning':'Unknown physical scale, taxonomy and sample independence; masks are source polygon or box-component proxies, may omit structures. No hallucinated detail.','assets':rows};(O/'manifest.json').write_text(json.dumps(out,indent=2)+'\n');print('Saved',len(rows),'unresized source crops with native support masks; physical scales unknown.')
if __name__=='__main__':main()
