#!/usr/bin/env python3
"""Deterministically generate and verify all Chapter 16 convolution/IoU data."""
import argparse, json, pathlib
X=[[1,2,0,1],[3,1,2,2],[0,1,3,1],[2,2,1,0]]; K=[[1,0],[-1,1]]
windows=[]; Y=[]
for i in range(3):
 row=[]
 for j in range(3):
  terms=[X[i+u][j+v]*K[u][v] for u in range(2) for v in range(2)]; value=sum(terms)
  windows.append({'at':[i,j],'terms':terms,'sum':value}); row.append(value)
 Y.append(row)
P=[1,1,4,4]; G=[2,0,5,3]; iw=max(0,min(P[2],G[2])-max(P[0],G[0])); ih=max(0,min(P[3],G[3])-max(P[1],G[1]))
area=lambda b:(b[2]-b[0])*(b[3]-b[1]); inter=iw*ih; union=area(P)+area(G)-inter
case={'schema':1,'license':'CC BY 4.0','creator':'本项目 computer-vision-editor','convention':{'operation':'cross-correlation','origin':'top-left','index_base':0,'stride':[1,1],'padding':[0,0]},'input':X,'kernel':K,'output_shape':[3,3],'output':Y,'windows':windows,'boxes':{'coordinate_convention':'continuous half-open [x1,y1,x2,y2)','prediction':P,'ground_truth':G,'intersection_wh':[iw,ih],'prediction_area':area(P),'ground_truth_area':area(G),'intersection_area':inter,'union_area':union,'iou_fraction':[2,7],'iou_decimal':inter/union,'threshold':0.5,'matched':inter/union>=0.5,'protocol':{'class_match_required':True,'prediction_order':'confidence descending, ties by prediction index ascending','ground_truth_choice':'largest IoU among unmatched same-class truths','iou_tie_break':'ground-truth index ascending','one_to_one':True,'no_candidate':'false positive'},'counts':{'tp':0,'fp':1,'fn':1,'precision':0.0,'recall':0.0}}}
if __name__=='__main__':
 p=argparse.ArgumentParser(); p.add_argument('--json',action='store_true'); p.add_argument('--check',type=pathlib.Path); a=p.parse_args()
 if Y!=[[-1,3,0],[4,3,0],[0,0,2]] or inter*7!=union*2: raise SystemExit('internal recomputation failure')
 if a.check:
  try: actual=json.loads(a.check.read_text())
  except Exception as e: raise SystemExit(f'cannot read check target: {e}')
  if actual!=case: raise SystemExit(f'published JSON drift: {a.check}')
 print(json.dumps(case,ensure_ascii=False,indent=2) if a.json else 'CH16 DATA PASSED: full case; output 3x3; 9 windows; intersection=4; union=14; IoU=2/7; threshold=0.5 unmatched.')
