"""Posthoc per-plane comparator from preserved toy experiment candidates."""
import hashlib,json
from pathlib import Path
import numpy as np
import r38_synthetic_crossings as base
ROOT=Path(__file__).resolve().parents[1];OUT=ROOT/'results/l46'
def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()
def main():
 src=OUT/'results.json';rows=[]
 for row in json.loads(src.read_text())['records']:
  with np.load(OUT/row['archive'],allow_pickle=False) as f:
   n,h,w=map(int,f['candidate_shape']);masks=np.unpackbits(f['candidate_bits'])[:n*h*w].reshape(n,h,w).astype(bool);refs=f['full_masks'];zs=f['candidate_z']
  per=[]
  for z in range(5):
   items=[m for m,zi in zip(masks,zs) if zi==z];per.append({'z':z,'candidates':len(items),'matching':base.assign(refs,items,.5)})
  if per[2]['matching']!=row['automatic_scores']['single_middle']['all']:raise ValueError('Middle plane does not reproduce')
  rows.append({'pair':row['pair'],'kind':row['kind'],'archive_sha256':sha(OUT/row['archive']),'planes':per})
 (OUT/'plane-audit.json').write_text(json.dumps({'format':'l46-plane-audit-v1','results_sha256':sha(src),'script_sha256':sha(Path(__file__)),'records':rows,'warning':'Posthoc per-plane comparison on the same toy simulation; choosing the best plane after seeing labels is an oracle.'},indent=2)+'\n');print('Verified all five per-plane candidate sets against toy references.')
if __name__=='__main__':main()
