"""Posthoc test of exact-constant-image abstention on stored drift controls."""
import hashlib,json,sys
from pathlib import Path
import numpy as np
import l47_registration_experiment as experiment
ROOT=Path(__file__).resolve().parents[1];OUT=ROOT/'results/l47';PREV=ROOT/'results/r58';sys.path.insert(0,str(ROOT/'diatom_pilot'))
from phase_alignment_checked import checked_alignment
def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()
def main():
 src=OUT/'registration.json';records=json.loads(src.read_text())['records'];rows=[]
 for r in records:
  with np.load(PREV/r['archive'],allow_pickle=False) as f:original=f['planes'].copy()
  texture=r['texture'];base=original if texture=='normal' else np.clip(128+.10*(original.astype('float32')-128),0,255).astype('uint8') if texture=='low_contrast' else np.full_like(original,128)
  shifted=np.stack([experiment.warp_image(base[z],*r['injected_shifts'][z]) for z in range(5)])
  for item in r['planes']:
   z=item['z'];checked=checked_alignment(shifted[2],shifted[z]);old=r['estimates'][z]
   if checked['estimate'] is not None and any(abs(checked['estimate'][k]-old[k])>1e-5 for k in ('dx','dy','response')):raise ValueError('Phase estimate mismatch')
   rows.append({'dataset':r['dataset'],'pair':r['pair'],'texture':texture,'step_x':r['step_x'],'z':z,'prior_guard_accepted':item['guard_accepted'],'checked_status':checked['status'],'prior_response':old['response'],'delta_error_px':item['delta_error_px']})
 (OUT/'guard-audit.json').write_text(json.dumps({'format':'l47-guard-audit-v1','registration_sha256':sha(src),'guard_code_sha256':sha(ROOT/'diatom_pilot/phase_alignment_checked.py'),'script_sha256':sha(Path(__file__)),'records':rows,'warning':'Posthoc exact-constant input check; nonconstant does not mean sufficient texture or correct alignment. All scenes previously inspected.'},indent=2)+'\n');print('Audited',len(rows),'nonmiddle phase estimates with exact-constant abstention.',flush=True)
if __name__=='__main__':main()
