"""Session 97: independent scalar replay and saved-result grading.

Uses standard-library arithmetic and the retained log tables. No decoder fit,
SAT solver, parameter change or plaintext search is performed.
"""
from pathlib import Path
import hashlib
import json
import math

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(cipher,starts,ends,key,skips,model,selective,initial):
    assert len(cipher)==len(starts)==len(ends) and len(key)==13
    assert len(set(skips))==len(skips)
    assert all(type(k)==int and 0<=k<29 for k in key)
    skip=set(skips);assert all(0<=p<len(cipher) and cipher[p]==0 and selective for p in skip)
    output=[];inverse=[];phase=initial;a=b=29;score=0.
    for i,c in enumerate(cipher):
        if starts[i]:a=b=29
        if i in skip:p=0;inverse.append(0);score+=math.log(.5)
        else:
            p=(c-key[phase])%29;inverse.append((p+key[phase])%29);phase=(phase+1)%13
            if selective and p==0:score+=math.log(.5)
        score+=model['log'][a][b][p]
        if ends[i]:score+=model['log'][b][p][29]
        output.append(p);a,b=b,p
    assert inverse==cipher
    return output,phase,score


def main():
    plan=READ('paired_recovery_plan.json');spec=READ('paired_recovery_execution.json')
    data=READ('paired_recovery_inputs.json');result=READ('paired_recovery_results.json');checks=READ('paired_recovery_checks.json')
    for name,wanted in plan['input_hashes'].items():assert SHA(name)==wanted,name
    for field,name in [('driver_sha256','paired_recovery.py'),('plan_sha256','paired_recovery_plan.json'),('input_sha256','paired_recovery_inputs.json'),('engine_sha256','rotation_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('paired_recovery_execution.json')
    assert result['checks_sha256']==SHA('paired_recovery_checks.json')
    assert len(data['positive_pairs'])==len(result['positive_pairs'])==9
    assert len(data['null_pairs'])==len(result['null_pairs'])==54 and len(result['supplied_key_pairs'])==9
    models=READ('recovery_benchmark_models.json')['models']
    refs={g['name']:g['values'] for g in READ('increment_calibration_sources.json')['groups']}
    positive={p['id']:p for p in data['positive_pairs']}
    all_cases={c['id']:c for pair in data['positive_pairs']+data['null_pairs'] for c in pair['streams']}
    row_lookup={};audits=[];mismatches=[];rune_count=0
    for category in ['positive_pairs','null_pairs','supplied_key_pairs']:
      for pair in result[category]:
        agreement=[]
        for stream in pair['streams']:
            case=all_cases[stream['id']];raw=stream['raw'];grade=stream['grade'];cut=case['cut'];model=models[case['source']]
            assert raw['status']==grade['status']=='completed'
            pre=raw['prefix'];post=raw['suffix'];key=raw['key']
            before=replay(case['cipher'][:cut],case['starts'][:cut],case['ends'][:cut],key,pre['skips'],model,case['selective_F'],0)
            after=replay(case['cipher'][cut:],case['starts'][cut:],case['ends'][cut:],key,post['skips'],model,case['selective_F'],pre['end_phase'])
            assert before[0]==pre['plaintext'] and after[0]==post['plaintext']
            assert before[1]==pre['end_phase'] and after[1]==post['end_phase']
            assert abs(before[2]-pre['score'])<1e-7 and abs(after[2]-post['score'])<1e-7
            output=before[0]+after[0];rune_count+=len(output)
            assert DIGEST(output)==grade['decoded_output_sha256']
            assert abs(grade['prefix_mean_score']-before[2]/(cut+sum(case['ends'][:cut])))<1e-9
            assert abs(grade['continuation_mean_score']-after[2]/(len(output)-cut+sum(case['ends'][cut:])))<1e-9
            anchor=output[case['anchor_start']:case['anchor_start']+6]
            assert anchor==grade['anchor_output'];agreement.append(anchor)
            if category!='supplied_key_pairs':row_lookup[case['id']]=stream
            record={'id':case['id'],'category':category,'runes':len(output),'exact_scalar_reencryption':True,'scores_match':True}
            if pair['kind']!='shuffled':
                gold=refs[case['source']][:len(output)]
                assert DIGEST(gold)==case['gold_plaintext_sha256']
                accuracy=lambda a,b:sum(x==y for x,y in zip(a,b))/len(b)
                assert grade['key_exact']==(key==case['planted_key'])
                assert grade['full_output_exact']==(output==gold)
                assert grade['anchor_exact']==(anchor==gold[-6:])
                assert abs(grade['prefix_rune_accuracy']-accuracy(output[:cut],gold[:cut]))<1e-12
                assert abs(grade['continuation_rune_accuracy']-accuracy(output[cut:],gold[cut:]))<1e-12
                assert grade['prefix_terminal_phase_exact']==(pre['end_phase']==case['gold_prefix_end_phase'])
                expected=bool(key==case['planted_key'] and accuracy(output[:cut],gold[:cut])>=.95 and accuracy(output[cut:],gold[cut:])>=.95 and anchor==gold[-6:] and pre['end_phase']==case['gold_prefix_end_phase'])
                assert grade['positive_case_passed']==expected
                if category=='supplied_key_pairs':assert key==case['planted_key']
                record.update(key_exact=grade['key_exact'],anchor_exact=grade['anchor_exact'],full_message_exact=grade['full_output_exact'])
                if category=='positive_pairs' and output!=gold:
                    masks=case['planted_F_offsets'];gold_pre=replay(case['cipher'][:cut],case['starts'][:cut],case['ends'][:cut],key,[p for p in masks if p<cut],model,case['selective_F'],0)
                    gold_post=replay(case['cipher'][cut:],case['starts'][cut:],case['ends'][cut:],key,[p-cut for p in masks if p>=cut],model,case['selective_F'],gold_pre[1])
                    assert gold_pre[0]+gold_post[0]==gold
                    indexes=[i for i,(a,b) in enumerate(zip(gold,output)) if a!=b]
                    oracle=next(s for p in result['supplied_key_pairs'] for s in p['streams'] if s['id']==case['id'])
                    same=oracle['grade']['decoded_output_sha256']==grade['decoded_output_sha256'];assert same
                    advantage=pre['score']+post['score']-gold_pre[2]-gold_post[2]
                    assert advantage>0 and key==case['planted_key']
                    mismatches.append({'id':case['id'],'mismatch_offsets':indexes,
                        'gold_values':[gold[i] for i in indexes],'returned_values':[output[i] for i in indexes],
                        'cipher_values':[case['cipher'][i] for i in indexes],
                        'prefix_score_advantage':pre['score']-gold_pre[2],
                        'continuation_score_advantage':post['score']-gold_post[2],
                        'supplied_key_returns_same_output':same,
                        'classification':'Fixed-model path ranking; correct key recovered. No repair applied.'})
            audits.append(record)
        assert pair['anchor_agreement']==(agreement[0]==agreement[1])
        if pair['kind']!='shuffled':assert pair['positive_pair_passed']==bool(agreement[0]==agreement[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'])
        matching=[p for p in result['null_pairs'] if p['positive_pair_id']==pos['id']];assert len(matching)==9
        for m in comparison['margins']:
            v=pos['streams'][m['stream']]['grade'][m['metric']]
            maximum=max(p['streams'][m['stream']]['grade'][m['metric']] for p in matching)
            assert m['positive']==v and m['null_maximum']==maximum and m['strictly_exceeds_all_nulls']==(v>maximum)
        assert comparison['gate']==('pass' if all(m['strictly_exceeds_all_nulls'] for m in comparison['margins']) else 'fail')
    assert result['positive_gate']==result['score_gate']==result['overall_gate']=='pass'
    assert result['positive_stream_keys_exact']==18 and result['positive_stream_messages_exact']==16
    assert result['positive_pairs_anchor_agree']==9 and result['null_pairs_anchor_agree']==0
    assert len(audits)==144 and len(mismatches)==2
    output={'session':97,'results_sha256':SHA('paired_recovery_results.json'),'audit_driver_sha256':SHA('paired_recovery_audit.py'),
        'audits':audits,'path_ranking_diagnostics':mismatches,'scalar_streams_replayed':len(audits),
        'rune_outputs_replayed':rune_count,'all_gates_independently_recomputed':True,'new_decoder_calls':0}
    target=ROOT/'paired_recovery_audit.json'
    if target.exists():assert READ(target.name)==output,'Preserve differing audit outcomes.'
    else:target.write_text(json.dumps(output,indent=2)+'\n')
    print(json.dumps({'scalar_streams_verified':len(audits),'runes_replayed':rune_count,'gate':'pass','path_ranking_misses':len(mismatches),'new_decoder_calls':0}))


if __name__=='__main__':main()
