"""Verify downloaded crops, source taxon grouping and all physical-scale transforms."""
import collections,csv,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/diversity-fetch';META=Path('/tmp/ude-metadata.csv');CAL=R/'results/r112/design/native-scenes/background-calibration.json'
def sha(p):
 h=hashlib.sha256()
 with open(p,'rb') as f:
  for b in iter(lambda:f.read(1048576),b''):h.update(b)
 return h.hexdigest()
p=json.loads((O/'assets.json').read_text());s=json.loads((O/'selection.json').read_text());d=json.loads((O/'download-report.json').read_text());a=json.loads((O/'duplicate-audit.json').read_text());assert sha(O/'selection.json')==p['selection_sha256']==d['selection_sha256']==a['selection_sha256'] and sha(O/'download-report.json')==p['download_sha256']==a['download_report_sha256'] and sha(META)==p['metadata_sha256'] and sha(CAL)==p['calibration_sha256'] and sha(R/'research/r112_diverse_calibration.py')==p['script_sha256'];assert len(p['records'])==len(s['rows'])==120;assert [v['annotation_id'] for v in p['records']]==[v['annotation_id'] for v in s['rows']];ids={x['annotation_id'] for x in s['rows']};meta={}
with META.open(newline='',encoding='utf-8-sig') as f:
 for x in csv.DictReader(f):
  if x['annotation_id'] in ids:meta[x['annotation_id']]=x
assert set(meta)==ids;bg=json.loads(CAL.read_text())['scenes'][:8];species=collections.defaultdict(set);short=0
for i,(item,orig) in enumerate(zip(p['records'],s['rows'])):
 m=meta[item['annotation_id']];path=O/item['source_crop'];image=np.asarray(Image.open(path).convert('L'));h,w=image.shape;assert sha(path)==item['source_sha256'] and item['source_dimensions_px']==[w,h] and item['source_genus']==m['genus']==orig['genus'] and item['source_species']==m['species']==orig['species'] and item['source_subspecies']==m['subspecies']==orig['subspecies'] and item['source_annotation_shape']==m['shape'] and item['source_annotation_points_global']==json.loads(m['points']);assert item['source_slide_group']==orig['source_slide']==m['image_filename'].split('.Chunk')[0] and item['source_slide_group'] not in s['excluded_previously_selected_slide_names'];bbox=[int(m[k]) for k in ('bbox_x0','bbox_y0','bbox_x1','bbox_y1')];assert item['source_annotation_bbox_global']==bbox;delta=[w-(bbox[2]-bbox[0]+1),h-(bbox[3]-bbox[1]+1)];assert item['crop_vs_annotation_bbox_delta_px']==delta;short+=int(any(v<0 for v in delta));b=bg[i%len(bg)];tx=b['background_um_per_pixel_x'];ty=b['background_um_per_pixel_y'];assert item['academy_target_slide']==b['slide'] and item['source_scale_um_px']==[.09,.09] and item['target_scale_um_px']==[tx,ty];tw=max(1,round(w*.09/tx));th=max(1,round(h*.09/ty));out=O/item['scaled_crop'];assert item['scaled_dimensions_px']==[tw,th] and sha(out)==item['scaled_sha256'] and np.array_equal(np.asarray(Image.open(out)),cv2.resize(image,(tw,th),interpolation=cv2.INTER_AREA));species[item['source_species']].add(item['source_slide_group'])
assert len(species)==30 and all(len(v)==4 for v in species.values());print(json.dumps({'assets':len(p['records']),'source_taxa':len(species),'slide_groups':len({x['source_slide_group'] for x in p['records']}),'shorter_than_metadata_box':short,'exact_duplicate_groups':len(a['duplicate_groups']),'checks':'Reconstructed all crop hashes, recorded metadata, slide-group selection and physical resampling. No independent biological identity, taxonomy, quality or scale validation.'},indent=2))
