"""Session 97: frozen paired hidden-key recovery and unforced anchor checks.

No unsolved text and no joint fitting. Reuse unchanged Session 89 decoder.
Run prepare, checks, benchmark; raw results and every failure are retained.
"""
from pathlib import Path
import argparse
import hashlib
import itertools
import json
import math
import random

import numpy as np
import rotation_recovery as rotation

old=rotation.old
ROOT=old.ROOT
PLAN=ROOT/'paired_recovery_plan.json'
INPUT=ROOT/'paired_recovery_inputs.json'
SPEC=ROOT/'paired_recovery_execution.json'
CHECKS=ROOT/'paired_recovery_checks.json'
RESULTS=ROOT/'paired_recovery_results.json'
SOURCES=['welcome','koan','divinity']
PUBLIC=['cipher','starts','ends','cut','period','decoder_seed','selective_F']


def read(path):return json.loads(path.read_text())
def sha(path):return hashlib.sha256(path.read_bytes()).hexdigest()
def dump(path,value):path.write_text(json.dumps(value,indent=2,ensure_ascii=False)+'\n')


def public_case(case):return {name:case[name] for name in PUBLIC}


def payload_hash(case,model):
    public=public_case(case)
    header=f"fit_rotations {len(public['cipher'])} {public['cut']} 13 8 6 {public['decoder_seed']} {int(public['selective_F'])} 0"
    lines=[header]+[' '.join(map(str,public[n])) for n in ['cipher','starts','ends']]
    lines+=[' '.join(format(float(v),'.17g') for v in np.asarray(model['log']).ravel()),
            ' '.join(format(float(v),'.17g') for v in model['unigram_log'])]
    return hashlib.sha256(('\n'.join(lines)+'\n').encode()).hexdigest()


def anchors(plain,words):
    signatures={}
    for a,b in zip(words,words[1:]):
        if len(a['values'])==len(b['values'])==3:
            start=a['rune_offset'];end=b['rune_offset']+3
            signatures.setdefault(tuple(plain[start:end]),[]).append(start)
    choices=[]
    for signature,positions in signatures.items():
        for a,b in itertools.combinations(positions,2):
            if a>=320 and b>=a+6:choices.append((a,b,signature))
    assert choices
    return min(choices)


def layout(words,length):
    starts=[0]*length;ends=[0]*length
    for word in words:
        a=word['rune_offset'];b=a+len(word['values'])
        if b<=length:starts[a]=1;ends[b-1]=1
    assert starts[0] and ends[-1]
    cut=max(i+1 for i,end in enumerate(ends) if end and i+1<=int(.6*length))
    return starts,ends,cut


def encrypt(plain,key,skips):
    cipher=[];phase=0
    for i,value in enumerate(plain):
        if i in skips:assert value==0;cipher.append(0)
        else:cipher.append((value+key[phase])%29);phase=(phase+1)%13
    return cipher


def verify_archives():
    for name,wanted in read(PLAN)['input_hashes'].items():assert sha(ROOT/name)==wanted,name
    rotation.verify_spec()
    fixture=read(ROOT/'rotation_recovery_fixtures.json')
    assert fixture['passed'] and len(fixture['policy_checks'])==64
    assert fixture['execution_sha256']==sha(ROOT/'rotation_recovery_execution.json')


def prepare():
    assert not SPEC.exists() and not INPUT.exists() and not CHECKS.exists() and not RESULTS.exists()
    verify_archives();refs,words,_=old.sources_and_models();models=rotation.load_models()
    previous=[c['planted_key'] for name in ['recovery_benchmark_cases.json','rotation_recovery_cases.json']
              for c in read(ROOT/name)['cases'] if c['planted_key'] is not None]
    positive=[];nulls=[];all_keys=[];selections=[]
    for source_index,source in enumerate(SOURCES):
        a,b,signature=anchors(refs[source],words[source]);lengths=[a+6,b+6]
        selections.append({'source':source,'anchor_starts':[a,b],'anchor_values':list(signature),
            'message_runes':lengths,'messages_are_nested_group_prefixes':True})
        assert models[source]['excluded_group']==source and source not in models[source]['training_groups']
        for kind_index,(kind,trial) in enumerate([('no_skip',0),('selective_F',0),('selective_F',1)]):
            selective=kind=='selective_F';seed=330197+100*source_index+(10*trial+1 if selective else 0)
            rng=random.Random(seed);plains=[refs[source][:n] for n in lengths];masks=[]
            for si,plain in enumerate(plains):
                fs=[i for i,p in enumerate(plain) if p==0]
                skips={p for ordinal,p in enumerate(fs) if selective and ordinal%2==((trial+si)%2)}
                if selective:assert skips
                masks.append(skips)
            phases=[(n-6-len([p for p in masks[si] if p<n-6]))%13 for si,n in enumerate(lengths)]
            required={(phases[0]+j)%13:(-signature[j])%29 for j in range(6)}
            key0=[rng.choice([v for v in range(29) if v!=required[slot]]) if slot in required else rng.randrange(29) for slot in range(13)]
            key1=[None]*13
            for j in range(13):
                value=key0[(phases[0]+j)%13]
                key1[(phases[1]+j)%13]=value if j<6 else rng.choice([v for v in range(29) if v!=value])
            keys=[key0,key1]
            assert key0!=key1 and all(len(set(k))>1 and k not in previous for k in keys)
            all_keys.extend(keys);pair_id=f'{source}_{kind}_{trial}';streams=[]
            for si,(plain,key,skips) in enumerate(zip(plains,keys,masks)):
                starts,ends,cut=layout(words[source],len(plain));anchor=len(plain)-6
                assert anchor>=cut
                cipher=encrypt(plain,key,skips)
                case={'id':f'{pair_id}_s{si}','source':source,'kind':kind,'trial':trial,'stream':si,
                    'construction_seed':seed,'cipher':cipher,'starts':starts,'ends':ends,'cut':cut,
                    'period':13,'selective_F':selective,
                    'decoder_seed':970000+100*source_index+10*kind_index+si,
                    'anchor_start':anchor,'anchor_length':6,'planted_key':key,
                    'planted_F_offsets':sorted(skips),'gold_plaintext_sha256':old.digest(plain),
                    'gold_prefix_end_phase':(cut-sum(p<cut for p in skips))%13}
                case['public_fit_payload_sha256']=payload_hash(case,models[source]);streams.append(case)
            assert streams[0]['cipher'][-6:]==streams[1]['cipher'][-6:]
            assert 0 not in streams[0]['cipher'][-6:]
            pair={'id':pair_id,'source':source,'kind':kind,'trial':trial,'streams':streams,
                  'gold_anchor_values':list(signature),'gold_anchor_phases':phases}
            positive.append(pair)
            if not selective:continue
            for replicate in range(9):
                null_seed=330297+1000*source_index+100*trial+replicate;rng=random.Random(null_seed);changed=[]
                for case in streams:
                    cut=case['cut'];anchor=case['anchor_start']
                    pre=case['cipher'][:cut].copy();post=case['cipher'][cut:anchor].copy()
                    rng.shuffle(pre);rng.shuffle(post)
                    clone={**case,'id':f'{pair_id}_null{replicate}_s{case["stream"]}',
                        'kind':'shuffled','cipher':pre+post+case['cipher'][anchor:],
                        'planted_key':None,'planted_F_offsets':None,'gold_plaintext_sha256':None,
                        'gold_prefix_end_phase':None,'null_seed':null_seed}
                    clone['public_fit_payload_sha256']=payload_hash(clone,models[source]);changed.append(clone)
                nulls.append({'id':f'{pair_id}_null{replicate}','positive_pair_id':pair_id,
                    'source':source,'kind':'shuffled','trial':trial,'replicate':replicate,
                    'null_seed':null_seed,'streams':changed})
    assert len(positive)==9 and len(nulls)==54 and len({tuple(k) for k in all_keys})==18
    dump(INPUT,{'session':97,'selections':selections,'positive_pairs':positive,'null_pairs':nulls,
        'source_overlap_limit':'Six nested messages from three related solved groups; new arrays do not create new prose.'})
    dump(SPEC,{'session':97,'driver_sha256':sha(Path(__file__)),'plan_sha256':sha(PLAN),
        'input_sha256':sha(INPUT),'engine_sha256':sha(rotation.ENGINE),
        'models_sha256':sha(ROOT/'recovery_benchmark_models.json'),
        'positive_pairs':9,'null_pairs':54,'unknown_key_fits':126,'supplied_key_diagnostics':18,
        'restarts':8,'sweeps':6,'process_timeout_seconds':120,
        'public_case_fields':PUBLIC,'equality_or_anchor_coordinates_passed_to_fit':False,
        'saved_before_checks_and_benchmark':True,'no_unsolved_text_fitting':True})
    print('PREPARED',json.dumps(selections),flush=True)


def verify():
    spec=read(SPEC)
    for field,path in [('driver_sha256',Path(__file__)),('plan_sha256',PLAN),('input_sha256',INPUT),
                       ('engine_sha256',rotation.ENGINE),('models_sha256',ROOT/'recovery_benchmark_models.json')]:
        assert spec[field]==sha(path),field
    verify_archives()


def checks():
    verify();assert not CHECKS.exists();data=read(INPUT);models=rotation.load_models()
    positives={p['id']:p for p in data['positive_pairs']};count=0
    for pair in data['positive_pairs']+data['null_pairs']:
        assert len(pair['streams'])==2
        for case in pair['streams']:
            n=len(case['cipher']);cut=case['cut'];anchor=case['anchor_start']
            assert len(case['starts'])==len(case['ends'])==n and case['ends'][cut-1]
            assert case['starts'][-6:]==[1,0,0,1,0,0] and case['ends'][-6:]==[0,0,1,0,0,1]
            assert anchor==n-6 and anchor>=cut and 0 not in case['cipher'][-6:]
            assert set(public_case(case))==set(PUBLIC)
            assert case['public_fit_payload_sha256']==payload_hash(case,models[case['source']]);count+=1
            if pair['kind']=='shuffled':
                basis=positives[pair['positive_pair_id']]['streams'][case['stream']]
                for start,end in [(0,cut),(cut,anchor),(anchor,n)]:assert sorted(case['cipher'][start:end])==sorted(basis['cipher'][start:end])
                for name in ['starts','ends','cut','decoder_seed']:assert case[name]==basis[name]
                assert case['cipher'][anchor:]==basis['cipher'][anchor:]
        assert pair['streams'][0]['cipher'][-6:]==pair['streams'][1]['cipher'][-6:]
    rotation.compile_engine();rng=np.random.default_rng(330197);fixtures=[]
    for trial in range(4):
        period=trial+1;cipher=rng.integers(0,29,8).tolist();cipher[0]=cipher[2]=cipher[-1]=0
        starts=[1,0,1,1,0,0,1,0];ends=[0,1,1,0,0,1,0,1];key=rng.integers(0,29,period).tolist();phase=trial%period
        model={'log':rng.normal(-3,1,(30,30,30)),'unigram_log':np.full(29,-math.log(29))}
        for permit in (False,True):
            case={'cipher':cipher,'starts':starts,'ends':ends,'cut':3,'period':period,'selective_F':permit,'decoder_seed':970900+trial}
            answer=rotation.run(public_case(case),model,'oracle',key,phase)
            assert answer['status']=='completed'
            pre,post=answer['prefix'],answer['suffix']
            before=old.scalar(cipher[:3],starts[:3],ends[:3],key,set(pre['skips']),model,permit,phase)
            after=old.scalar(cipher[3:],starts[3:],ends[3:],key,set(post['skips']),model,permit,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']
            a,_=old.brute(cipher[:3],starts[:3],ends[:3],key,model,permit,phase)
            b,_=old.brute(cipher[3:],starts[3:],ends[3:],key,model,permit,pre['end_phase'])
            assert abs(a-pre['score'])<1e-8 and abs(b-post['score'])<1e-8
            assert abs(before[2]-pre['score'])<1e-8 and abs(after[2]-post['score'])<1e-8
            fixtures.append({'trial':trial,'period':period,'selective_F':permit,'scalar_and_exhaustive_agree':True})
    dump(CHECKS,{'session':97,'execution_sha256':sha(SPEC),'passed':True,
        'archived_64_policy_checks_verified':True,'public_fit_payloads_verified':count,
        'layout_source_exclusion_and_null_invariants':True,'short_path_fixtures':fixtures,
        'benchmark_fits_run':0})
    print('CHECKS PASS:126payloads,archive hashes,eight exhaustive path checks',flush=True)


def evaluate(case,answer,model,gold):
    grade=old.grade(case,answer,model,gold)
    if answer['status']!='completed':return {'raw':answer,'grade':grade}
    output=answer['prefix']['plaintext']+answer['suffix']['plaintext']
    anchor=output[case['anchor_start']:case['anchor_start']+6]
    grade['anchor_output']=anchor
    if gold is not None:
        grade['anchor_exact']=anchor==gold[-6:]
        grade['prefix_terminal_phase_exact']=answer['prefix']['end_phase']==case['gold_prefix_end_phase']
        grade['positive_case_passed']=bool(grade['key_exact'] and grade['prefix_rune_accuracy']>=.95
            and grade['continuation_rune_accuracy']>=.95 and grade['anchor_exact'] and grade['prefix_terminal_phase_exact'])
    return {'raw':answer,'grade':grade}


def fit_pair(pair,models,refs,oracle=False):
    outputs=[]
    for case in pair['streams']:
        model=models[case['source']];assert payload_hash(case,model)==case['public_fit_payload_sha256']
        answer=rotation.run(public_case(case),model,'oracle' if oracle else 'fit_rotations',case['planted_key'] if oracle else None)
        gold=None if pair['kind']=='shuffled' else refs[case['source']][:len(case['cipher'])]
        outputs.append({'id':case['id'],**evaluate(case,answer,model,gold)})
    complete=all(o['grade']['status']=='completed' for o in outputs)
    agreement=outputs[0]['grade']['anchor_output']==outputs[1]['grade']['anchor_output'] if complete else None
    row={k:pair[k] for k in ['id','source','kind','trial']};row['streams']=outputs;row['anchor_agreement']=agreement
    if 'positive_pair_id' in pair:row['positive_pair_id']=pair['positive_pair_id'];row['replicate']=pair['replicate']
    if pair['kind']!='shuffled':row['positive_pair_passed']=bool(complete and agreement and all(o['grade'].get('positive_case_passed',False) for o in outputs))
    row['supplied_key_diagnostic']=oracle
    return row


def benchmark():
    verify();assert read(CHECKS)['passed'] and read(CHECKS)['execution_sha256']==sha(SPEC)
    assert not RESULTS.exists();rotation.compile_engine();data=read(INPUT);models=rotation.load_models();refs,_,_=old.sources_and_models()
    positive=[];nulls=[];oracles=[]
    def checkpoint():dump(RESULTS,{'session':97,'complete':False,'positive_pairs':positive,'null_pairs':nulls,'supplied_key_pairs':oracles})
    for pair in data['positive_pairs']:
        row=fit_pair(pair,models,refs);positive.append(row);checkpoint()
        print('POSITIVE',pair['id'],row['positive_pair_passed'],[r['grade'].get('key_exact') for r in row['streams']],flush=True)
    for pair in data['null_pairs']:
        row=fit_pair(pair,models,refs);nulls.append(row);checkpoint()
        print('NULL',pair['id'],'anchor_agreement',row['anchor_agreement'],flush=True)
    for pair in data['positive_pairs']:
        row=fit_pair(pair,models,refs,True);oracles.append(row);checkpoint()
        print('ORACLE',pair['id'],[r['grade'].get('full_output_exact') for r in row['streams']],flush=True)
    positives_complete=all(s['grade']['status']=='completed' for r in positive for s in r['streams'])
    positive_gate='unresolved' if not positives_complete else ('pass' if all(r['positive_pair_passed'] for r in positive) else 'fail')
    comparisons=[]
    for row in positive:
        if row['kind']=='no_skip':continue
        matching=[r for r in nulls if r['positive_pair_id']==row['id']];assert len(matching)==9
        complete=all(s['grade']['status']=='completed' for r in [row]+matching for s in r['streams'])
        margins=[]
        if complete:
            for si in range(2):
                for metric in ['prefix_mean_score','continuation_mean_score']:
                    margins.append({'stream':si,'metric':metric,'positive':row['streams'][si]['grade'][metric],
                        'null_maximum':max(r['streams'][si]['grade'][metric] for r in matching),
                        'strictly_exceeds_all_nulls':row['streams'][si]['grade'][metric]>max(r['streams'][si]['grade'][metric] for r in matching)})
        comparisons.append({'id':row['id'],'gate':'unresolved' if not complete else ('pass' if all(m['strictly_exceeds_all_nulls'] for m in margins) else 'fail'),'margins':margins})
    score_gate='unresolved' if any(c['gate']=='unresolved' for c in comparisons) else ('pass' if all(c['gate']=='pass' for c in comparisons) else 'fail')
    overall='unresolved' if 'unresolved' in [positive_gate,score_gate] else ('pass' if positive_gate==score_gate=='pass' else 'fail')
    verify()
    dump(RESULTS,{'session':97,'complete':True,'positive_pairs':positive,'null_pairs':nulls,'supplied_key_pairs':oracles,
        'positive_gate':positive_gate,'score_gate':score_gate,'overall_gate':overall,'score_comparisons':comparisons,
        'unknown_key_fits':126,'supplied_key_diagnostics':18,'execution_sha256':sha(SPEC),'checks_sha256':sha(CHECKS),
        'positive_stream_keys_exact':sum(s['grade'].get('key_exact',False) for r in positive for s in r['streams']),
        'positive_stream_messages_exact':sum(s['grade'].get('full_output_exact',False) for r in positive for s in r['streams']),
        'positive_pairs_anchor_agree':sum(r['anchor_agreement'] is True for r in positive),
        'null_pairs_anchor_agree':sum(r['anchor_agreement'] is True for r in nulls),
        'no_unsolved_text_fitting':True,'no_new_plaintext':True})
    print('COMPLETE',json.dumps({'positive_gate':positive_gate,'score_gate':score_gate,'overall_gate':overall}),flush=True)


if __name__=='__main__':
    parser=argparse.ArgumentParser();parser.add_argument('stage',choices=['prepare','checks','benchmark'])
    globals()[parser.parse_args().stage]()
