"""Session98 standard-library replay. No decoder calls or parameter fitting."""
from pathlib import Path
import hashlib,json,math,random
ROOT=Path(__file__).resolve().parent
read=lambda name:json.loads((ROOT/name).read_text())
sha=lambda name:hashlib.sha256((ROOT/name).read_bytes()).hexdigest()
digest=lambda values:hashlib.sha256(bytes(values)).hexdigest()

def replay(c,s,e,mask,key,skips,model,selective,phase):
    assert len(c)==len(s)==len(e)==len(mask) and len(key)==13
    assert len(set(skips))==len(skips) and all(0<=i<len(c) and c[i]==0 and selective for i in skips)
    assert all(type(v)==int and 0<=v<29 for v in key)
    skip=set(skips);plain=[];score=0.;a=b=29
    for i,value in enumerate(c):
        if s[i]:a=b=29
        if i in skip:p=0;inverse=0
        else:p=(value-key[phase])%29;inverse=(p+key[phase])%29;phase=(phase+1)%13
        assert inverse==value
        if mask[i]:
            score+=model['log'][a][b][p]
            if selective and (i in skip or p==0):score+=math.log(.5)
            if e[i]:score+=model['log'][b][p][29]
        plain.append(p);a,b=b,p
    return plain,phase,score

def main():
    plan=read('early_anchor_recovery_next_plan.json');spec=read('early_anchor_recovery_execution.json');data=read('early_anchor_recovery_inputs.json');result=read('early_anchor_recovery_results.json');checks=read('early_anchor_recovery_checks.json')
    for name,value in plan['input_hashes'].items():assert sha(name)==value,name
    for field,name in [('driver_sha256','early_anchor_recovery.py'),('plan_sha256','early_anchor_recovery_next_plan.json'),('input_sha256','early_anchor_recovery_inputs.json'),('engine_sha256','early_anchor_recovery_engine.cpp'),('models_sha256','recovery_benchmark_models.json')]:assert spec[field]==sha(name)
    assert result['complete'] and checks['passed'] and result['execution_sha256']==checks['execution_sha256']==sha('early_anchor_recovery_execution.json')
    assert result['checks_sha256']==sha('early_anchor_recovery_checks.json')
    assert len(data['positive_pairs'])==len(result['positive_pairs'])==len(result['supplied_key_pairs'])==6
    assert len(data['null_pairs'])==len(result['null_pairs'])==27
    assert len(checks['fixtures'])==64 and len(checks['paired_perturbation_probes'])==6
    models=read('recovery_benchmark_models.json')['models'];positive={p['id']:p for p in data['positive_pairs']}
    cases={c['id']:c for p in data['positive_pairs']+data['null_pairs'] for c in p['streams']}
    for p in data['null_pairs']:
        rng=random.Random(p['null_seed'])
        for c in p['streams']:
            basis=positive[p['positive_pair_id']]['streams'][c['stream']];expected=basis['cipher'].copy()
            for lo,hi in [(0,c['cut']),(c['cut'],len(expected))]:
                ix=[i for i in range(lo,hi) if c['score_mask'][i]];values=[expected[i] for i in ix];rng.shuffle(values)
                for i,v in zip(ix,values):expected[i]=v
            assert expected==c['cipher']
    all_keys=[c['planted_key'] for p in data['positive_pairs'] for c in p['streams']]
    assert len({tuple(k) for k in all_keys})==12
    previous=[c['planted_key'] for name in ['recovery_benchmark_cases.json','rotation_recovery_cases.json'] for c in read(name)['cases']]
    previous += [c['planted_key'] for p in read('paired_recovery_inputs.json')['positive_pairs'] for c in p['streams']]
    assert all(k not in previous for k in all_keys)
    for p in data['positive_pairs']:
        m=models[p['source']];assert m['excluded_group']==p['source'] and p['source'] not in m['training_groups']
        for si,c in enumerate(p['streams']):
            gold=c['gold_plaintext'];assert digest(gold)==c['gold_plaintext_sha256']
            assert len(gold)==[1524,3316][si] and c['anchor_start']==[28,3310][si]
            assert c['score_mask'][c['anchor_start']:c['anchor_start']+6]==[0]*6
            assert c['starts'][c['anchor_start']:c['anchor_start']+6]==[1,0,0,1,0,0]
            assert c['ends'][c['anchor_start']:c['anchor_start']+6]==[0,0,1,0,0,1]
            sk=c['planted_F_offsets'];cut=c['cut'];phase=0;encoded=[]
            for i,value in enumerate(gold):
                if i in sk:assert value==0;encoded.append(0)
                else:encoded.append((value+c['planted_key'][phase])%29);phase=(phase+1)%13
            assert encoded==c['cipher'] and c['gold_prefix_end_phase']==(cut-sum(i<cut for i in sk))%13
    audits=[];misses=[];runes=0
    for category in ['positive_pairs','null_pairs','supplied_key_pairs']:
        for pair in result[category]:
            anchors=[];complete=True
            for stream in pair['streams']:
                c=cases[stream['id']];a=stream['raw'];g=stream['grade'];cut=c['cut'];m=models[c['source']]
                if a['status']!='completed':
                    assert g['status']==a['status'];complete=False;audits.append({'id':c['id'],'category':category,'status':a['status']});continue
                assert g['status']=='completed';output=[];scores=[]
                for label,lo,hi,phase in [('prefix',0,cut,0),('suffix',cut,len(c['cipher']),a['prefix']['end_phase'])]:
                    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'],m,c['selective_F'],phase)
                    assert x[0]==v['plaintext'] and x[1]==v['end_phase'] and abs(x[2]-v['score'])<1e-7
                    output+=x[0];scores.append(x[2])
                runes+=len(output);assert digest(output)==g['decoded_output_sha256']
                for metric,lo,hi,score in [('prefix',0,cut,scores[0]),('continuation',cut,len(output),scores[1])]:
                    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']-score/den)<1e-9
                anchor=output[c['anchor_start']:c['anchor_start']+6];assert anchor==g['anchor_output'];anchors.append(anchor)
                rec={'id':c['id'],'category':category,'runes':len(output),'scalar_scores_and_reencryption':True}
                if pair['kind']!='shuffled':
                    gold=c['gold_plaintext'];acc=lambda x,y:sum(a==b for a,b in zip(x,y))/len(y)
                    exact=a['key']==c['planted_key'];anchor_exact=anchor==gold[c['anchor_start']:c['anchor_start']+6];phase_exact=a['prefix']['end_phase']==c['gold_prefix_end_phase']
                    assert g['key_exact']==exact and g['anchor_exact']==anchor_exact and g['full_output_exact']==(output==gold) and g['prefix_terminal_phase_exact']==phase_exact
                    assert g['skip_mask_exact']==(a['prefix']['skips']+[i+cut for i in a['suffix']['skips']]==c['planted_F_offsets'])
                    assert abs(g['prefix_rune_accuracy']-acc(output[:cut],gold[:cut]))<1e-12 and abs(g['continuation_rune_accuracy']-acc(output[cut:],gold[cut:]))<1e-12
                    gate=exact and anchor_exact and phase_exact and acc(output[:cut],gold[:cut])>=.95 and acc(output[cut:],gold[cut:])>=.95
                    assert g['positive_case_passed']==gate
                    if category=='supplied_key_pairs':assert exact
                    rec.update(key_exact=exact,anchor_exact=anchor_exact,full_message_exact=output==gold)
                    if category=='positive_pairs' and output!=gold:
                        indices=[i for i,(x,y) in enumerate(zip(output,gold)) if x!=y]
                        oracle=next(s for p in result['supplied_key_pairs'] for s in p['streams'] if s['id']==c['id'])
                        same=oracle['grade'].get('decoded_output_sha256')==g['decoded_output_sha256']
                        advantages=None
                        if exact:
                            sk=c['planted_F_offsets'];g0=replay(c['cipher'][:cut],c['starts'][:cut],c['ends'][:cut],c['score_mask'][:cut],a['key'],[i for i in sk if i<cut],m,c['selective_F'],0)
                            g1=replay(c['cipher'][cut:],c['starts'][cut:],c['ends'][cut:],c['score_mask'][cut:],a['key'],[i-cut for i in sk if i>=cut],m,c['selective_F'],g0[1]);assert g0[0]+g1[0]==gold
                            advantages=[scores[0]-g0[2],scores[1]-g1[2]]
                        misses.append({'id':c['id'],'key_exact':exact,'anchor_exact':anchor_exact,'mismatch_offsets':indices,'gold_values':[gold[i] for i in indices],'returned_values':[output[i] for i in indices],'cipher_values':[c['cipher'][i] for i in indices],'supplied_key_same_output':same,'score_advantages_over_planted_path':advantages})
                audits.append(rec)
            assert pair['anchor_agreement']==(anchors[0]==anchors[1] if complete else None)
            if pair['kind']!='shuffled':assert pair['positive_pair_passed']==bool(complete and anchors[0]==anchors[1] and all(s['grade']['positive_case_passed'] for s in pair['streams']))
    for comparison in result['score_comparisons']:
        pos=next(p for p in result['positive_pairs'] if p['id']==comparison['id']);nulls=[p for p in result['null_pairs'] if p['positive_pair_id']==pos['id']];assert len(nulls)==9
        complete=all(s['grade']['status']=='completed' for p in [pos]+nulls for s in p['streams'])
        for v in comparison['margins']:
            p=pos['streams'][v['stream']]['grade'][v['metric']];q=max(n['streams'][v['stream']]['grade'][v['metric']] for n in nulls)
            assert v['positive']==p and v['null_maximum']==q and v['strictly_exceeds_all_nulls']==(p>q)
        gate='unresolved' if not complete else 'pass' if all(v['strictly_exceeds_all_nulls'] for v in comparison['margins']) else 'fail';assert gate==comparison['gate']
    pg='unresolved' if any(s['grade']['status']!='completed' for p in result['positive_pairs'] for s in p['streams']) else 'pass' if all(p['positive_pair_passed'] for p in result['positive_pairs']) else 'fail'
    sg='unresolved' if any(c['gate']=='unresolved' for c in result['score_comparisons']) else 'pass' if all(c['gate']=='pass' for c in result['score_comparisons']) else 'fail'
    overall='unresolved' if 'unresolved' in [pg,sg] else 'pass' if pg==sg=='pass' else 'fail';assert (pg,sg,overall)==(result['positive_gate'],result['score_gate'],result['overall_gate'])
    assert len(audits)==78
    for field,expected in [('positive_stream_keys_exact',sum(s['grade'].get('key_exact',False) for p in result['positive_pairs'] for s in p['streams'])),('positive_stream_messages_exact',sum(s['grade'].get('full_output_exact',False) for p in result['positive_pairs'] for s in p['streams'])),('positive_pairs_anchor_agree',sum(p['anchor_agreement'] is True for p in result['positive_pairs'])),('null_pairs_anchor_agree',sum(p['anchor_agreement'] is True for p in result['null_pairs']))]:assert result[field]==expected
    out={'session':98,'results_sha256':sha('early_anchor_recovery_results.json'),'audit_driver_sha256':sha('early_anchor_recovery_audit.py'),'audits':audits,'path_diagnostics':misses,'scalar_streams_checked':len(audits),'rune_outputs_replayed':runes,'positive_gate':pg,'score_gate':sg,'overall_gate':overall,'all_gates_independently_recomputed':True,'new_decoder_calls':0}
    path=ROOT/'early_anchor_recovery_audit.json'
    if path.exists():assert json.loads(path.read_text())==out
    else:path.write_text(json.dumps(out,indent=2)+'\n')
    print(json.dumps({k:out[k] for k in ['scalar_streams_checked','rune_outputs_replayed','overall_gate','new_decoder_calls']}))
if __name__=='__main__':main()
