"""Verify diversity proposal artifacts; this does not establish biological correctness."""
import collections,hashlib,json
from pathlib import Path
import numpy as np
from PIL import Image
from r112_new_taxa_masks import points_for
R=Path(__file__).resolve().parents[1];D=R/'results/r112/new-taxa';O=D/'mask-hypotheses';sha=lambda x:hashlib.sha256(x.read_bytes()).hexdigest()
p=json.loads((O/'protocol.json').read_text());out=json.loads((O/'results.json').read_text());assets=json.loads((D/'development-assets.json').read_text())['records'];assert len(assets)==len(out['records']) and p['development_assets_sha256']==sha(D/'development-assets.json') and out['protocol_sha256']==sha(O/'protocol.json') and out['script_sha256']==sha(R/'research/r112_new_taxa_masks.py'); counts=collections.Counter();taxa=set()
for a,r in zip(assets,out['records']):
 assert a['annotation_id']==r['annotation_id'] and a['source_species']==r['source_species'] and sha(D/a['source_crop'])==a['source_sha256']==r['source_sha256'];assert np.allclose(points_for(a),r['source_points_xy']);w,h=a['source_dimensions_px'];assert Image.open(D/a['source_crop']).size==(w,h);m=[]
 for name in ('center','minus','plus'):
  info=r['masks'][name];f=O/info['file'];assert sha(f)==info['sha256'];im=np.asarray(Image.open(f).convert('L'));assert im.shape==(h,w) and set(np.unique(im)).issubset({0,255});mask=im>0;assert int(mask.sum())==info['area_px'];m.append(mask)
 scores=[]
 for x,y in ((0,1),(0,2),(1,2)):
  union=(m[x]|m[y]).sum();scores.append(float((m[x]&m[y]).sum()/union) if union else 0.)
 cover=float(m[0].mean());triage='consistent-unverified' if min(scores)>=.75 and .03<=cover<=.75 else 'needs-inspection';assert np.allclose(scores,r['pairwise_iou']) and abs(cover-r['center_mask_crop_fraction'])<1e-12 and triage==r['triage'];counts[triage]+=1
 if triage=='consistent-unverified':taxa.add(a['source_species'])
summary={'source_crops':len(assets),'candidate_masks':len(assets)*3,'triage':dict(counts),'source_named_species_with_consistent_proposal':len(taxa),'checks':'Source and proposal hashes, dimensions, shared prompt helper, mask areas, pairwise agreement and triage recomputed. No model replay or independent biological validation; consistency is not accuracy.'};(O/'verify.log').write_text(json.dumps(summary,indent=2)+'\n');print(json.dumps(summary,indent=2))
