"""Audit saved proposal files, geometry, hashes and triage, not correctness."""
import argparse,collections,ctypes,hashlib,json,os,signal
from pathlib import Path
import cv2,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/species-breadth-extension';O=D/'mask-hypotheses';W=Path('/tmp/mobile_sam.pt');sha=lambda p:hashlib.sha256(Path(p).read_bytes()).hexdigest()
def main():
 parent=os.getppid();assert ctypes.CDLL(None,use_errno=True).prctl(1,signal.SIGTERM)==0
 if parent!=os.getppid():raise RuntimeError('launcher exited')
 parser=argparse.ArgumentParser();parser.add_argument('--limit',type=int,default=0);args=parser.parse_args();cv2.setNumThreads(2);p=json.loads((O/'protocol.json').read_text());assert sha(D/'assets.json')==p['source_assets_sha256'] and sha(D/'verify.json')==p['source_verify_sha256'] and sha(W)==p['model_sha256'] and sha(R/'research/r112_new_taxa_masks.py')==p['prompt_helper_sha256'];sources=json.loads((D/'assets.json').read_text())['records'];sources=sources[:args.limit] if args.limit else sources;counts=collections.Counter();missing=[]
 for r in sources:
  record=O/'records'/(r['annotation_id']+'.json')
  if not record.exists():missing.append(r['annotation_id']);continue
  x=json.loads(record.read_text());source=D/r['source_crop'];assert sha(source)==r['source_sha256']==x['source_sha256'] and x['protocol_sha256']==sha(O/'protocol.json') and x['source_species']==r['source_species'] and x['source_genus']==r['source_genus'] and x['source_site_component']==r['source_site_component'];w,h=r['source_dimensions_px'];assert Image.open(source).size==(w,h) and np.allclose(points_for({**r,'source_annotation_bbox_global':r['source_bbox_global']}),x['source_points_xy']);factor=min(1.,512/max(w,h));iw,ih=max(1,round(w*factor)),max(1,round(h*factor));ox,oy=(512-iw)//2,(512-ih)//2;assert x['inference_input_size_px']==[iw,ih] and x['inference_padding_offset_xy']==[ox,oy] and np.allclose(x['inference_points_xy'],[[ox+a*iw/w,oy+b*ih/h] for a,b in x['source_points_xy']]);m=[]
  for k in ('center','minus','plus'):
   v=x['masks'][k];path=O/v['file'];assert sha(path)==v['sha256'];arr=np.asarray(Image.open(path).convert('L'));assert arr.shape==(h,w) and set(np.unique(arr)).issubset({0,255});mask=arr>0;assert int(mask.sum())==v['area_px'];m.append(mask)
  pairs=[]
  for a,b in ((0,1),(0,2),(1,2)):
   u=int((m[a]|m[b]).sum());pairs.append(int((m[a]&m[b]).sum())/u if u else 0.)
  coverage=float(m[0].mean());status='consistent-unverified' if min(pairs)>=.75 and .03<=coverage<=.75 else 'needs-inspection';assert np.allclose(pairs,x['pairwise_iou']) and abs(coverage-x['center_mask_crop_fraction'])<1e-12 and status==x['triage'];counts[status]+=1
 if not args.limit:
  assert len(sources)==1054
  manifest=json.loads((O/'results.json').read_text());assert manifest['protocol_sha256']==sha(O/'protocol.json') and manifest['script_sha256']==sha(R/'research/r112_breadth_depth_extension_masks.py') and manifest['source_count']==len(sources) and manifest['completed_count']==sum(counts.values()) and manifest['missing_ids']==missing
  stored={x['annotation_id']:x for x in manifest['records']};assert len(stored)==manifest['completed_count']
  for r in sources:
   if r['annotation_id'] not in missing:assert stored[r['annotation_id']]==json.loads((O/'records'/(r['annotation_id']+'.json')).read_text())
 out={'format':'r112-breadth-extension-mask-verification-v1','protocol_sha256':sha(O/'protocol.json'),'verifier_sha256':sha(Path(__file__)),'requested_sources':len(sources),'verified_records':sum(counts.values()),'missing_ids':missing,'triage':dict(counts),'checks':'Source and mask hashes, source prompt helper, model-coordinate mapping, output dimensions, pixel values, areas, overlap and geometric triage recomputed. Does not replay model inference or validate biological labels, masks or independence.'};path=O/('pilot-verify.json' if args.limit else 'verify.json');path.write_text(json.dumps(out,indent=2)+'\n');print(json.dumps({k:out[k] for k in ('requested_sources','verified_records','triage')},indent=2))
if __name__=='__main__':main()
