"""Validate flagged review membership, source hashes, overlays, and feedback checks."""
import json
from pathlib import Path
import cv2,numpy as np
from PIL import Image,ImageDraw
from diatom_pilot.ude_scaleup_dataset import sha256
from diatom_pilot.validate_mask_feedback import validate
R=Path(__file__).resolve().parents[1];O=R/'results/r112/gated-risk-review';A=R/'results/r112/gated-mask-risk-audit';ROOTS={'scaleup':R/'results/r112/species-scaleup','breadth':R/'results/r112/species-breadth'};b=json.loads((O/'batch.json').read_text());risk=json.loads((A/'results.json').read_text());
for f,h in b['inputs_sha256'].items():assert sha256(R/f)==h,f
expected=sorted(risk['unique_sources'],key=lambda x:(-(x['selected_source_coverage']>.75),-x['selected_source_coverage'],x['source_name'],x['annotation_id']));assert len(expected)==len(b['cases'])==366;seen=set()
for case,item in zip(b['cases'],expected):
 ident=case['id'];assert ident==item['annotation_id'] and ident not in seen and case['source_pool']==item['source_pool'] and case['review_pass']==(1 if item['selected_source_coverage']>.75 else 2);seen.add(ident);rec=json.loads((R/item['proposal_record_path']).read_text());assert sha256(R/item['proposal_record_path'])==item['proposal_record_sha256'] and case['source_sha256']==rec['source_sha256']==item['source_crop_sha256'] and case['source_name']==item['source_name']==rec['source_species'] and case['target_point_xy']==rec['source_points_xy'][0] and case['proposal_sha256']=={k:rec['masks'][k]['sha256'] for k in ('center','minus','plus')};assert sha256(R/item['source_crop_path'])==item['source_crop_sha256']
 for k,img in case['images'].items():assert k in ('source','center','minus','plus') and sha256(O/img['path'])==img['sha256']
 for k in ('center','minus','plus'):assert sha256(ROOTS[item['source_pool']]/'mask-hypotheses'/rec['masks'][k]['file'])==rec['masks'][k]['sha256']
indices=sorted(set([0,125,126,365]+[next(i for i,x in enumerate(expected) if x['source_pool']==pool) for pool in ('scaleup','breadth')]))
for i in indices:
 case=b['cases'][i];item=expected[i];rec=json.loads((R/item['proposal_record_path']).read_text());src=np.asarray(Image.open(R/item['source_crop_path']).convert('L'));masks={k:np.asarray(Image.open(ROOTS[item['source_pool']]/'mask-hypotheses'/rec['masks'][k]['file']).convert('L'))>0 for k in ('center','minus','plus')};cx,cy=case['target_point_xy']
 for k in ('source','center','minus','plus'):
  rgb=np.repeat(src[:,:,None],3,axis=2).astype(np.float32)
  if k!='source':
   mask=masks[k];rgb[mask]=.65*rgb[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;rgb[edge]=[255,80,25]
  im=Image.fromarray(np.rint(rgb).clip(0,255).astype('uint8'));d=ImageDraw.Draw(im);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'][k]['path'])))
case=b['cases'][0];row={'id':case['id'],'source_sha256':case['source_sha256'],'proposal_sha256':case['proposal_sha256'],'choice':'unsure','target':'unsure','notes':'','role':'nonexpert'};p={'format':'r112-source-mask-review-feedback-v1','batch_sha256':sha256(O/'batch.json'),'records':[row]};assert validate(p,O/'batch.json')['valid_records']==1
for kind in ('wrong_batch','unknown_id','bad_hash','bad_choice','duplicate'):
 x=json.loads(json.dumps(p))
 if kind=='wrong_batch':x['batch_sha256']='0'*64
 elif kind=='unknown_id':x['records'][0]['id']='unknown'
 elif kind=='bad_hash':x['records'][0]['proposal_sha256']['plus']='0'*64
 elif kind=='bad_choice':x['records'][0]['choice']='approved'
 else:x['records'].append(x['records'][0])
 try:validate(x,O/'batch.json');raise AssertionError('accepted '+kind)
 except ValueError:pass
out={'format':'r112-gated-risk-review-verify-v1','batch_sha256':sha256(O/'batch.json'),'cases':len(seen),'priority_cases':sum(x['review_pass']==1 for x in b['cases']),'source_name_strings':len({x['source_name'] for x in b['cases']}),'overlay_indices_replayed':indices,'checks':'All source membership, proposal/crop hashes, priority order and 1464 overlay file hashes checked; selected overlay sets reconstructed. Feedback validation accepts a valid record and rejects mismatched batch, unknown/duplicate ID, mask hash and invalid choice. No biological correctness or expert adjudication is established.'};(O/'verify.json').write_text(json.dumps(out,indent=2)+'\n');print(json.dumps(out,indent=2))
