"""Verify slide split, download integrity, quarantine and development transformations."""
import collections,csv,hashlib,json,zlib
from pathlib import Path
import cv2,numpy as np
from PIL import Image
R=Path(__file__).resolve().parents[1];O=R/'results/r112/species-depth';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()
s=json.loads((O/'selection.json').read_text());d=json.loads((O/'download-report.json').read_text());p=json.loads((O/'screen-protocol.json').read_text());screen=json.loads((O/'similarity-screen.json').read_text());assets=json.loads((O/'development-assets.json').read_text());assert sha(O/'selection.json')==d['selection_sha256']==p['selection_sha256']==assets['selection_sha256'];assert sha(O/'screen-protocol.json')==screen['protocol_sha256'] and sha(O/'download-report.json')==screen['download_report_sha256']==assets['download_report_sha256'] and sha(O/'similarity-screen.json')==assets['screen_sha256'];assert sha(META)==s['metadata_sha256']==assets['metadata_sha256'] and sha(CAL)==assets['calibration_sha256'] and sha(R/'research/r112_depth_development.py')==assets['script_sha256'];assert not d['cross_split_exact_image_duplicates'];rows=s['rows'];ids={r['annotation_id'] for r in rows};dl={r['annotation_id']:r for r in d['images']};assert len(rows)==len(ids)==len(dl)==300 and ids==set(dl);groups=collections.defaultdict(set);species=collections.defaultdict(collections.Counter)
for r in rows:
 groups[r['source_slide']].add(r['split']);species[r['species']][r['split']]+=1;pfile=O/r['local_file'];b=pfile.read_bytes();assert hashlib.sha256(b).hexdigest()==dl[r['annotation_id']]['sha256'] and len(b)==dl[r['annotation_id']]['size'] and f'{zlib.crc32(b)&0xffffffff:08x}'==dl[r['annotation_id']]['archive_crc32']
assert len(groups)==60 and len(species)==10 and all(len(v)==1 for v in groups.values()) and all(c=={'development':20,'validation_candidate':5,'test_candidate':5} for c in species.values()) and not(set(groups)&set(s['excluded_previously_inspected_slide_names']));quarantine=set(screen['quarantined_new_ids']);flagids=set()
for flag in screen['flags']:
 assert flag['distance']<=4;flagids.add(flag['left']['id'])
 if flag['kind']=='cross_partition':flagids.add(flag['right']['id'])
assert quarantine==flagids;eligible={r['annotation_id'] for r in rows if r['split']=='development'}-quarantine;assert {r['annotation_id'] for r in assets['records']}==eligible;metadata={}
with META.open(newline='',encoding='utf-8-sig') as f:
 for r in csv.DictReader(f):
  if r['annotation_id'] in eligible:metadata[r['annotation_id']]=r
assert set(metadata)==eligible;cal=json.loads(CAL.read_text())['scenes'][:8]
for i,r in enumerate(assets['records']):
 m=metadata[r['annotation_id']];path=O/r['source_crop'];im=np.asarray(Image.open(path).convert('L'));h,w=im.shape;assert sha(path)==r['source_sha256'] and r['source_dimensions_px']==[w,h] and r['source_genus']==m['genus'] and r['source_species']==m['species'] and r['source_subspecies']==m['subspecies'] and r['source_annotation_shape']==m['shape'] and r['source_annotation_points_global']==json.loads(m['points']);c=cal[i%len(cal)];sx,sy=c['background_um_per_pixel_x'],c['background_um_per_pixel_y'];tw=max(1,round(w*.09/sx));th=max(1,round(h*.09/sy));out=O/r['scaled_crop'];assert r['target_slide']==c['slide'] and r['source_scale_um_px']==[.09,.09] and r['target_scale_um_px']==[sx,sy] and r['scaled_dimensions_px']==[tw,th] and sha(out)==r['scaled_sha256'] and np.array_equal(np.asarray(Image.open(out)),cv2.resize(im,(tw,th),interpolation=cv2.INTER_AREA));assert r['split']=='development'
print(json.dumps({'downloaded':len(rows),'slide_groups':len(groups),'taxa':len(species),'partition_counts':dict(collections.Counter(r['split'] for r in rows)),'quarantined':len(quarantine),'usable_development_candidates':len(eligible),'checks':'All archive CRCs/SHA, split groups, quarantines, metadata, target scale and development image resampling reconstructed. Does not prove sample independence, taxonomy, mask quality or model performance.'},indent=2))
