"""Re-run three central original-model batches to test cached-inference fidelity."""
import hashlib,json
from pathlib import Path
import cv2,numpy as np,torch
from PIL import Image
from ultralytics.models.sam import Predictor
ROOT=Path(__file__).resolve().parents[1];OUT=ROOT/'results/l67';SRC=ROOT/'results/r76'
def sha(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest()
def main():
 d=json.loads((OUT/'results.json').read_text());p=json.loads((OUT/'protocol.json').read_text());assert d['protocol_sha256']==sha(OUT/'protocol.json')
 for x in p['inputs']:
  if sha(x['path'])!=x['sha256']:raise ValueError('Changed input: '+x['path'])
 torch.set_num_threads(4);results=[]
 for row in d['records']:
  a=np.load(SRC/row['source_archive'],allow_pickle=False);shape=tuple(a['candidate_shape']);expected=np.unpackbits(a['candidate_bits'])[:int(np.prod(shape))].reshape(shape).astype(bool);image=np.asarray(Image.open(row['scene_rgb_path']).convert('RGB'));sam=Predictor(overrides={'model':'/tmp/mobile_sam.pt','task':'segment','mode':'predict','imgsz':512,'device':'cpu','retina_masks':True,'verbose':False,'save':False,'conf':0.0});sam.set_image(cv2.cvtColor(image,cv2.COLOR_RGB2BGR));diff=0.;exact=0
  for n in (108,120,132):
   pts=a['points'][n:n+12];out=sam(points=[[[int(x),int(y)]] for x,y in pts],labels=[[1] for _ in pts],verbose=False)[0];m=out.masks.data.cpu().numpy().astype(bool);q=out.boxes.conf.cpu().numpy();exact+=sum(np.array_equal(m[j],expected[n+j]) for j in range(12));diff=max(diff,float(np.max(np.abs(q-a['quality'][n:n+12]))))
  assert exact==36 and diff<=1e-6;results.append({'pair':row['pair'],'condition':row['condition'],'indices':list(range(108,144)),'exact_mask_count':exact,'max_quality_abs_delta':diff});print(row['pair'],row['condition'],exact,'masks exact',flush=True)
 (OUT/'central-reproduction.json').write_text(json.dumps({'format':'l67-central-reproduction-v1','input_results_sha256':sha(OUT/'results.json'),'script_sha256':sha(Path(__file__)),'results':results,'warning':'Checks 36 of 256 prompts per scene, plus the 12 separately checked during the main run; not every cached mask was rerun.'},indent=2)+'\n')
if __name__=='__main__':main()
