"""Verify bounded peak archives, reported ranks and input provenance."""
import hashlib,json
from pathlib import Path
import numpy as np
import l48_peak_hypotheses as exp
ROOT=Path(__file__).resolve().parents[1];OUT=ROOT/'results/l48';R59=ROOT/'results/r59'
def sha(p):return hashlib.sha256(p.read_bytes()).hexdigest()
def main():
 p=json.loads((OUT/'protocol.json').read_text())
 for k,v in p['inputs'].items():
  if sha(Path(v['file']))!=v['sha256']:raise ValueError('Input changed '+k)
 for name,h in p['prior_archives'].items():
  if sha(R59/name)!=h:raise ValueError('Prior archive changed '+name)
 data=json.loads((OUT/'results.json').read_text());rows=data['records']
 if len(rows)!=47:raise ValueError('Unexpected case count')
 for r in rows:
  with np.load(OUT/r['archive'],allow_pickle=False) as f:
   for window in ('none','hann'):
    surface=f['surface_'+window];v=r['variants'][window];peaks=v['peaks']
    if surface.shape!=(257,257) or not np.isfinite(surface).all() or len(peaks)>64 or v['total_peaks']<len(peaks):raise ValueError('Invalid surface or peak count')
    if any(abs(float(surface[q['dy']+128,q['dx']+128])-q['score'])>1e-6 or abs(q['dx'])>128 or abs(q['dy'])>128 for q in peaks):raise ValueError('Peak does not match surface')
    truth=r['truth'];alts=truth.get('alternatives',([truth['shift']] if 'shift' in truth else []));ranks=[exp.rank_of(peaks,x) for x in alts]
    if ranks!=v['reference_ranks']:raise ValueError('Incorrect reference rank')
   if r['set']=='new_synthetic':
    a=f['reference'];b=f['target'];truth=r['truth']
    if a.shape!=(768,768) or b.shape!=a.shape:raise ValueError('Invalid synthetic images')
    if truth['type']=='ambiguous' and not np.array_equal(a,b):raise ValueError('Synthetic alias is not exact')
    if truth['type']=='known_global':
     dx,dy=truth['shift']
     if not np.array_equal(np.roll(np.roll(a,dy,axis=0),dx,axis=1),b):raise ValueError('Synthetic shift changed')
 print(f'Verified {len(rows)} peak cases, archived surfaces, ranks, input hashes and synthetic controls.')
if __name__=='__main__':main()
