"""Verify unresized source crops and original annotation support at native resolution."""
import collections,hashlib,json
from pathlib import Path
import cv2,numpy as np
from PIL import Image
R=Path(__file__).resolve().parents[1];O=R/'results/r112/design/native-assets';p=json.loads((O/'manifest.json').read_text())
def sha(f):return hashlib.sha256(Path(f).read_bytes()).hexdigest()
assert sha(R/'research/r112_native_assets.py')==p['generator_sha256'] and sha(R/'results/r112/design/broader/manifest.json')==p['source_manifest_sha256'];cache={};shapes=[];genera=collections.Counter()
for item in p['assets']:
 s=item['source'];ip=R/s['image_path'];assert sha(ip)==s['image_sha256'];x0,y0,x1,y1=item['source_crop_xyxy'];source=np.asarray(Image.open(ip).convert('RGB'));crop=np.asarray(Image.open(O/item['source_image_crop']).convert('RGB'));assert sha(O/item['source_image_crop'])==item['source_image_crop_sha256'] and np.array_equal(crop,source[y0:y1,x0:x1]);assert sha(O/item['source_support_mask'])==item['source_support_mask_sha256'];mask=np.asarray(Image.open(O/item['source_support_mask']).convert('L'))>0
 if 'mask_path' in s:
  mp=R/s['mask_path'];assert sha(mp)==s['mask_sha256'] and sha(R/s['xml_path'])==s['xml_sha256'];key=s['mask_sha256']
  if key not in cache:
   _,cache[key]=cv2.connectedComponents((np.asarray(Image.open(mp).convert('L'))>0).astype('uint8'),connectivity=8)
  original=cache[key]==s['component_label']
 else:
  path=R/s['annotation_path'];assert sha(path)==s['annotation_sha256'];data=json.loads(path.read_text());ann=next(a for a in data['annotations'] if a['id']==s['annotation_id'] and a['image_id']==s['image_id']);original=np.zeros(source.shape[:2],np.uint8)
  for poly in ann['segmentation']:cv2.fillPoly(original,[np.rint(np.asarray(poly).reshape(-1,2)).astype('int32')],1)
  original=original.astype(bool)
 assert np.array_equal(mask,original[y0:y1,x0:x1]) and item['native_crop_size']==[x1-x0,y1-y0] and item['physical_scale_um_per_pixel'] is None and not item['eligible_for_independent_test'];genera[s['source_genus_folder']]+=1;shapes.append([x1-x0,y1-y0])
print(json.dumps({'assets':len(p['assets']),'source_genera':dict(genera),'minimum_longest_side':min(max(x) for x in shapes),'maximum_longest_side':max(max(x) for x in shapes),'checks':'Native crop pixels and polygon/component supports reconstructed byte-for-byte; scale, taxonomy, biological independence and usefulness for species remain unverified.'},indent=2))
