"""Verify review batch membership, provenance and source overlay examples."""
import collections,hashlib,json
from pathlib import Path
import cv2,numpy as np
from PIL import Image,ImageDraw
from diatom_pilot.ude_scaleup_dataset import UDEScaleupDataset
from diatom_pilot.validate_mask_feedback import validate
from r112_scaleup_synthetic_compare import sha
R=Path(__file__).resolve().parents[1];D=R/'results/r112/species-scaleup';O=R/'results/r112/source-mask-review';H=D/'mask-hypotheses';batch=json.loads((O/'batch.json').read_text());data=UDEScaleupDataset('training',include_unverified_masks=True);byid={x['annotation_id']:(i,x) for i,x in enumerate(data.entries)};counts=collections.Counter();seen=set()
assert batch['source_partition_sha256']==sha(D/'location-partitions.json') and batch['source_assets_sha256']==sha(D/'assets.json') and batch['mask_protocol_sha256']==sha(H/'protocol.json') and batch['mask_verification_sha256']==sha(H/'verify.json') and len(batch['cases'])==160
for case in batch['cases']:
 ident=case['id'];assert ident in byid and ident not in seen;seen.add(ident);_,e=byid[ident];rec=json.loads((H/'records'/f'{ident}.json').read_text());assert case['source_name']==e['source_species'] and case['source_sha256']==e['source_sha256']==rec['source_sha256'];assert case['model_triage']==rec['triage'] and case['target_point_xy']==rec['source_points_xy'][0];assert case['proposal_sha256']=={k:rec['masks'][k]['sha256'] for k in ('center','minus','plus')};counts[case['source_name']]+=1
 for k,item in case['images'].items():assert k in ('source','center','minus','plus') and sha(O/item['path'])==item['sha256']
assert len(counts)==80 and set(counts.values())=={2};assert sum(x['review_pass']==1 for x in batch['cases'])==80 and sum(x['review_pass']==2 and x['model_triage']=='needs-inspection' for x in batch['cases'])==80
for k in (0,79,80,159):
 case=batch['cases'][k];i,_=byid[case['id']];x=data[i];src=np.asarray(x['image']);target=case['target_point_xy']
 for name,mask in [('source',None),('center',x['weak_mask_proposals'][0]),('minus',x['weak_mask_proposals'][1]),('plus',x['weak_mask_proposals'][2])]:
  a=np.repeat(src[:,:,None],3,axis=2).astype(np.float32)
  if mask is not None:
   a[mask]=.65*a[mask]+.35*np.array([30,165,255],np.float32);edge=cv2.morphologyEx(mask.astype('uint8'),cv2.MORPH_GRADIENT,np.ones((3,3),np.uint8))>0;a[edge]=[255,80,25]
  im=Image.fromarray(np.rint(a).clip(0,255).astype('uint8'));d=ImageDraw.Draw(im);cx,cy=target;d.line((cx-4,cy,cx+4,cy),fill=(255,0,180),width=1);d.line((cx,cy-4,cx,cy+4),fill=(255,0,180),width=1);assert np.array_equal(np.asarray(im),np.asarray(Image.open(O/case['images'][name]['path'])))
case=batch['cases'][0];row={'id':case['id'],'source_sha256':case['source_sha256'],'proposal_sha256':case['proposal_sha256'],'choice':'unsure','target':'unsure','notes':'','role':'nonexpert'};payload={'format':'r112-source-mask-review-feedback-v1','batch_sha256':sha(O/'batch.json'),'records':[row]};assert validate(payload)['valid_records']==1
for changed in ('wrong_batch','unknown_id','bad_hash','bad_choice','duplicate'):
 x=json.loads(json.dumps(payload))
 if changed=='wrong_batch':x['batch_sha256']='0'*64
 elif changed=='unknown_id':x['records'][0]['id']='not-a-case'
 elif changed=='bad_hash':x['records'][0]['proposal_sha256']['center']='0'*64
 elif changed=='bad_choice':x['records'][0]['choice']='approved'
 else:x['records'].append(x['records'][0])
 try:validate(x);raise AssertionError('validator accepted '+changed)
 except ValueError:pass
result={'format':'r112-source-mask-review-verify-v1','batch_sha256':sha(O/'batch.json'),'cases':len(seen),'source_names':len(counts),'second_pass_inspection_cases':80,'overlay_indices_replayed':[0,79,80,159],'checks':'All case IDs verified as unique training members, labels and proposal hashes checked against source records, all 640 overlay file hashes checked and four complete sets reconstructed. Feedback validation accepted a valid record and rejected wrong batch, unknown/duplicate ID, wrong mask hash and invalid choice. This does not validate biology, names, masks, or reviewers.'};(O/'verify.json').write_text(json.dumps(result,indent=2)+'\n');print(json.dumps(result,indent=2))
