"""Describe proposal-area changes without assigning biological correctness."""
import collections,json
from pathlib import Path
import numpy as np
from PIL import Image
from diatom_pilot.ude_scaleup_dataset import sha256
R=Path(__file__).resolve().parents[1];G=R/'results/r112/gated-alternative-scenes';O=R/'results/r112/gated-mask-risk-audit';roots={'scaleup':R/'results/r112/species-scaleup','breadth':R/'results/r112/species-breadth'}
def main():
 assert not (O/'results.json').exists();m=json.loads((G/'manifest.json').read_text());v=json.loads((G/'verify.json').read_text());assert v['manifest_sha256']==sha256(G/'manifest.json');rows=[];unique={}
 for scene in m['records']:
  source='breadth' if scene['family']=='breadth' else 'scaleup'
  for i,x in enumerate(scene['instances']):
   if x['selected_proposal']=='center':continue
   path=R/x['proposal_record_path'];assert sha256(path)==x['proposal_record_sha256'];rec=json.loads(path.read_text());ident=x['annotation_id'];assert rec['annotation_id']==ident and rec['triage']=='needs-inspection';w,h=rec['source_dimensions_px'];area=w*h;center=rec['masks']['center'];selected=rec['masks'][x['selected_proposal']];assert selected['sha256']==x['selected_source_mask_sha256'] and area>0 and x['center_in_frame_support_pixels']>0
   entry={'family':scene['family'],'scene_id':scene['id'],'instance_index':i,'source_pool':source,'annotation_id':ident,'source_name':x['source_name'],'selected_proposal':x['selected_proposal'],'source_crop_path':str((roots[source]/rec['source_crop']).relative_to(R)),'source_crop_sha256':rec['source_sha256'],'proposal_record_path':x['proposal_record_path'],'proposal_record_sha256':x['proposal_record_sha256'],'center_source_area_px':center['area_px'],'selected_source_area_px':selected['area_px'],'source_crop_area_px':area,'center_source_coverage':center['area_px']/area,'selected_source_coverage':selected['area_px']/area,'center_in_frame_area_px':x['center_in_frame_support_pixels'],'selected_in_frame_area_px':x['in_frame_support_pixels'],'in_frame_area_ratio':x['in_frame_support_pixels']/x['center_in_frame_support_pixels'],'original_image_path':scene['original_image_path'],'candidate_image_path':str((G/scene['image']).relative_to(R))};rows.append(entry);key=(source,ident);u={k:entry[k] for k in ('source_pool','annotation_id','source_name','selected_proposal','source_crop_path','source_crop_sha256','proposal_record_path','proposal_record_sha256','center_source_area_px','selected_source_area_px','source_crop_area_px','center_source_coverage','selected_source_coverage')};assert key not in unique or unique[key]==u;unique[key]=u
 assert len(rows)==409 and len(unique)==366;un=list(unique.values());summary={'noncenter_placements':len(rows),'distinct_changed_sources':len(un),'selected_source_coverage_gt_0_75':sum(x['selected_source_coverage']>.75 for x in un),'selected_source_coverage_gt_0_90':sum(x['selected_source_coverage']>.90 for x in un),'center_source_coverage_gt_0_75':sum(x['center_source_coverage']>.75 for x in un),'selected_gt_0_75_center_le_0_75':sum(x['selected_source_coverage']>.75 and x['center_source_coverage']<=.75 for x in un),'selected_gt_0_90_center_le_0_90':sum(x['selected_source_coverage']>.9 and x['center_source_coverage']<=.9 for x in un),'placements_with_inframe_area_gt_5x':sum(x['in_frame_area_ratio']>5 for x in rows),'placements_with_inframe_area_gt_10x':sum(x['in_frame_area_ratio']>10 for x in rows)}
 out={'format':'r112-gated-mask-risk-audit-v1','candidate_manifest_sha256':sha256(G/'manifest.json'),'candidate_verification_sha256':sha256(G/'verify.json'),'script_sha256':sha256(Path(__file__)),'summary':summary,'unique_sources':un,'placements':rows,'warning':'Area and crop coverage are geometric review cues, not correctness or rejection thresholds. Some real specimens fill a crop, and tiny center masks may be wrong. Visual examples include very large rectangular or background-like proposals; shared-model agreement is not biological validation. Do not automatically promote this candidate rule or the candidate scene labels.'};(O/'results.json').write_text(json.dumps(out,indent=2)+'\n');print(json.dumps(summary,indent=2))
if __name__=='__main__':main()
