"""Session99 independent standard-library replay. No decoder calls."""
from pathlib import Path
import json,hashlib
from early_anchor_recovery_audit import replay
P=Path(__file__).resolve().parent
read=lambda n:json.loads((P/n).read_text())
sha=lambda n:hashlib.sha256((P/n).read_bytes()).hexdigest()
def main():
 r=read('real_pair_recovery_results.json');d=read('real_pair_recovery_cases.json');spec=read('real_pair_recovery_execution.json');checks=read('real_pair_recovery_checks.json');plan=read('real_pair_recovery_next_plan.json');model=read('first_section_model.json')
 for n,h in plan['input_hashes'].items():assert sha(n)==h
 for k,n in [('plan_sha256','real_pair_recovery_next_plan.json'),('driver_sha256','real_pair_recovery.py'),('cases_sha256','real_pair_recovery_cases.json'),('engine_sha256','early_anchor_recovery_engine.cpp'),('model_sha256','first_section_model.json')]:assert spec[k]==sha(n)
 assert checks['passed'] and r['complete'] and r['execution_sha256']==checks['execution_sha256']==sha('real_pair_recovery_execution.json') and r['checks_sha256']==sha('real_pair_recovery_checks.json')
 cases={c['id']:c for c in d['originals']+[c for p in d['null_pairs'] for c in p['streams']]};outputs={};records=[];count=0
 assert len(r['rows'])==20 and len(cases)==40
 assert [p['id'] for p in r['rows']]==[f'null{i:02d}' for i in range(19)]+['original']
 for pair in r['rows']:
  anchors=[];complete=True
  for s in pair['streams']:
   c=cases[s['id']];a=s['raw'];g=s['grade'];cut=c['cut']
   if a['status']!='completed':assert g['status']==a['status'];complete=False;records.append({'id':c['id'],'status':a['status']});continue
   out=[]
   for label,lo,hi,phase,metric in [('prefix',0,cut,0,'prefix'),('suffix',cut,len(c['cipher']),a['prefix']['end_phase'],'continuation')]:
    v=a[label];x=replay(c['cipher'][lo:hi],c['starts'][lo:hi],c['ends'][lo:hi],c['score_mask'][lo:hi],a['key'],v['skips'],model,True,phase)
    assert x[0]==v['plaintext'] and x[1]==v['end_phase'] and abs(x[2]-v['score'])<1e-7
    den=sum(c['score_mask'][i]*(1+c['ends'][i]) for i in range(lo,hi));assert g[metric+'_scored_events']==den and abs(g[metric+'_mean_score']-x[2]/den)<1e-9
    out+=x[0]
   assert hashlib.sha256(bytes(out)).hexdigest()==g['decoded_output_sha256'];anchor=out[c['anchor_start']:c['anchor_start']+6];assert anchor==g['anchor_output'];anchors.append(anchor);outputs[c['id']]=out;count+=len(out);records.append({'id':c['id'],'runes':len(out),'masked_score_phase_and_reencryption_pass':True})
  assert pair['anchor_agreement']==(anchors[0]==anchors[1] if complete else None)
 for v in r['comparisons']:
  si=[6,8].index(v['section_id']);metric=v['metric'];orig=r['rows'][-1]['streams'][si]['grade'][metric];null=[p['streams'][si]['grade'][metric] for p in r['rows'][:-1] if p['streams'][si]['raw']['status']=='completed']
  assert v['original']==orig and v['null_maximum']==max(null) and v['margin']==orig-max(null) and v['rank']==1+sum(n>=orig for n in null) and v['passed']==(len(null)==19 and orig>max(null))
 for w in r['singleton_checks']:
  si=[6,8].index(w['section_id']);c=d['originals'][si];value=outputs[c['id']][w['offset']];assert value==w['output']
  allowed=c['constraints']['AIO_all_singletons'][str(w['offset'])];assert w['allowed']==allowed and w['passed']==(value in allowed)
  assert w['eligible_prior_red_exemptions']==(str(w['offset']) in c['constraints']['AIO_prior_red_exemptions'])
 complete=all(s['raw']['status']=='completed' for p in r['rows'] for s in p['streams']);sg=complete and all(v['passed'] for v in r['comparisons']);wg=len(r['singleton_checks'])==27 and all(w['passed'] for w in r['singleton_checks'] if w['eligible_prior_red_exemptions']);pg=r['rows'][-1]['anchor_agreement']
 assert (sg,wg,pg)==(r['score_gate'],r['word_gate'],r['phrase_gate']);gate='unresolved' if not complete else 'pass' if sg and wg and pg else 'fail';assert r['overall_gate']==gate
 out={'session':99,'results_sha256':sha('real_pair_recovery_results.json'),'audit_code_sha256':sha('real_pair_recovery_audit.py'),'streams_checked':len(records),'runes_replayed':count,'records':records,'all_scores_ranks_word_and_phrase_gates_recomputed':True,'overall_gate':gate,'new_decoder_calls':0}
 target=P/'real_pair_recovery_audit.json'
 if target.exists():assert json.loads(target.read_text())==out
 else:target.write_text(json.dumps(out,indent=2)+'\n')
 print(json.dumps({k:out[k] for k in ['streams_checked','runes_replayed','overall_gate']}))
if __name__=='__main__':main()
