"""Session 88: hidden-plaintext recovery controls; never searches real text.

Python/NumPy plus a C++17 compiler. The decoder process receives ciphertext,
word flags and a target-excluding model. Gold plaintext is used only outside
that process for encryption and grading; an oracle mode separately receives K.
"""
from pathlib import Path
from collections import Counter
import argparse
import hashlib
import itertools
import json
import math
import random
import subprocess
import time

import numpy as np
from lp_core import ROOT, pages, R
from lexical_words import tokenize_words

PLAN = ROOT/'recovery_benchmark_plan.json'
ENGINE = ROOT/'recovery_benchmark_engine.cpp'
BINARY = ROOT.parents[1]/'.sites-runtime/recovery-engine'
TARGETS = ['welcome','koan','divinity','second_koan']
INDICES = {'warning':[0], 'welcome':[1,2], 'wisdom':[3], 'koan':[4,5,6,7],
           'divinity':[8,9,10,11], 'second_koan':[12,13], 'instruction':[14],
           'lp2_56':[71], 'lp2_57':[72]}


def sha(path): return hashlib.sha256(path.read_bytes()).hexdigest()
def digest(values): return hashlib.sha256(bytes(map(int,values))).hexdigest()
def dump(name,value):
    (ROOT/name).write_text(json.dumps(value,ensure_ascii=False,indent=2)+'\n')


def compile_engine():
    BINARY.parent.mkdir(parents=True,exist_ok=True)
    subprocess.run(['g++','-O3','-std=c++17',str(ENGINE),'-o',str(BINARY)],check=True)


def run_engine(case,model,mode='fit',key=None,phase=0,restarts=8,sweeps=6):
    header = f"{mode} {len(case['cipher'])} {case['cut']} 13 {restarts} {sweeps} {case['decoder_seed']} {int(case['selective_F'])} {phase}"
    if 'period' in case:
        header = f"{mode} {len(case['cipher'])} {case['cut']} {case['period']} {restarts} {sweeps} {case['decoder_seed']} {int(case['selective_F'])} {phase}"
    parts=[header]
    for name in ['cipher','starts','ends']: parts.append(' '.join(map(str,case[name])))
    parts.append(' '.join(format(float(x),'.17g') for x in np.asarray(model['log']).ravel()))
    parts.append(' '.join(format(float(x),'.17g') for x in model['unigram_log']))
    if mode=='oracle': parts.append(' '.join(map(str,key)))
    start=time.monotonic()
    try:
        result=subprocess.run([str(BINARY)],input='\n'.join(parts)+'\n',text=True,
                              capture_output=True,timeout=120,check=True)
    except subprocess.TimeoutExpired:
        return {'status':'unresolved_timeout','wall_limit_seconds':120}
    answer=json.loads(result.stdout);answer['status']='completed'
    answer['elapsed_seconds']=round(time.monotonic()-start,3)
    return answer


def scalar(cipher,starts,ends,key,skips,model,selective,phase=0):
    decoded=[];encoded=[];a=b=29;score=0.
    for i,c in enumerate(cipher):
        if starts[i]:a=b=29
        if i in skips:
            assert selective and c==0
            p=0;inverse=0;score+=math.log(.5)
        else:
            p=(c-key[phase])%29;inverse=(p+key[phase])%29
            phase=(phase+1)%len(key)
            if selective and p==0:score+=math.log(.5)
        score+=float(model['log'][a,b,p])
        if ends[i]:score+=float(model['log'][b,p,29])
        decoded.append(p);encoded.append(inverse);a,b=b,p
    assert encoded==list(cipher)
    return decoded,phase,score


def brute(cipher,starts,ends,key,model,selective,phase):
    fs=[i for i,c in enumerate(cipher) if c==0]
    best=-math.inf;count=0
    masks=itertools.product([False,True],repeat=len(fs)) if selective else [([False]*len(fs))]
    for choices in masks:
        skipped={i for i,yes in zip(fs,choices) if yes}
        _,_,score=scalar(cipher,starts,ends,key,skipped,model,selective,phase)
        if score>best+1e-9:best=score;count=1
        elif abs(score-best)<=1e-9:count+=1
    return best,count


def fixtures():
    compile_engine();rng=np.random.default_rng(330188)
    rows=[]
    for trial in range(32):
        n=8;period=1+trial%4
        cipher=rng.integers(0,29,n).tolist()
        if trial%4==0:cipher=[1 if x==0 else x for x in cipher]
        if trial%4==1:cipher[2:5]=[0,0,0]
        if trial%4==2:cipher[0]=cipher[-1]=0
        if trial%4==3:cipher=[0]*n
        starts=[1,0,1,1,0,0,1,0];ends=[0,1,1,0,0,1,0,1];cut=3
        key=rng.integers(0,29,period).tolist()
        if trial%3==0:key[0]=0
        model={'log':rng.normal(-3,1,(30,30,30)), 'unigram_log':np.full(29,-math.log(29))}
        phase=trial%period
        for permit in (False,True):
            case={'cipher':cipher,'starts':starts,'ends':ends,'cut':cut,'period':period,
                  'selective_F':permit,'decoder_seed':880000+trial}
            answer=run_engine(case,model,'oracle',key,phase)
            assert answer['status']=='completed'
            prefix,suffix=answer['prefix'],answer['suffix']
            before=scalar(cipher[:cut],starts[:cut],ends[:cut],key,set(prefix['skips']),model,permit,phase)
            after=scalar(cipher[cut:],starts[cut:],ends[cut:],key,set(suffix['skips']),model,permit,prefix['end_phase'])
            assert before[0]==prefix['plaintext'] and before[1]==prefix['end_phase']
            assert after[0]==suffix['plaintext'] and after[1]==suffix['end_phase']
            optimum,ties=brute(cipher[:cut],starts[:cut],ends[:cut],key,model,permit,phase)
            follow,follow_ties=brute(cipher[cut:],starts[cut:],ends[cut:],key,model,permit,prefix['end_phase'])
            assert abs(optimum-prefix['score'])<1e-8
            assert abs(follow-suffix['score'])<1e-8
            assert abs(before[2]-prefix['score'])<1e-8 and abs(after[2]-suffix['score'])<1e-8
            rows.append({'trial':trial,'period':period,'phase':phase,'selective_F':permit,
                         'cipher':cipher,'key':key,'prefix_score':optimum,
                         'suffix_score_at_frozen_state':follow,'prefix_optimal_masks':ties,
                         'suffix_optimal_masks':follow_ties,'exhaustive_score_match':True,
                         'scalar_replay_and_reencryption':True})
    out={'session':88,'plan_sha256':sha(PLAN),'driver_sha256':sha(Path(__file__)),
         'engine_source_sha256':sha(ENGINE),'fixtures':32,'policy_checks':rows,
         'compiler':subprocess.check_output(['g++','--version'],text=True).splitlines()[0],
         'saved_before_recovery_benchmark':True}
    dump('recovery_benchmark_fixtures.json',out)
    print(json.dumps({'fixtures':32,'policy_checks':len(rows),'all_passed':True}),flush=True)


def sources_and_models():
    manifest=json.loads((ROOT/'increment_calibration_sources.json').read_text())
    refs={g['name']:list(map(int,g['values'])) for g in manifest['groups']}
    words={}
    for name,indices in INDICES.items():
        source='%'.join(pages[i] for i in indices)
        words[name]=tokenize_words(source)
        assert sum(len(w['values']) for w in words[name])==len(refs[name])
    models={}
    for target in TARGETS:
        uni=np.ones(30)*.5;bc=np.zeros((30,30));tc=np.zeros((30,30,30))
        training=[]
        for name,plain in refs.items():
            if name==target:continue
            training.append(name)
            for w in words[name]:
                off=w['rune_offset'];p=plain[off:off+len(w['values'])]
                for a,b,c in zip([29,29]+p+[29],[29]+p+[29],p+[29]):
                    uni[c]+=1;bc[b,c]+=1;tc[a,b,c]+=1
        up=uni/uni.sum();bp=(bc+5*up)/(bc.sum(1,keepdims=True)+5)
        tp=(tc+5*bp[None,:,:])/(tc.sum(2,keepdims=True)+5)
        models[target]={'log':np.log(tp),'unigram_log':np.log(up[:29]/up[:29].sum()),
                        'excluded_group':target,'training_groups':training}
    return refs,words,models


def construct_cases(refs,words):
    cases=[]
    for index,name in enumerate(TARGETS):
        plain=refs[name];n=len(plain)
        starts=[0]*n;ends=[0]*n
        for w in words[name]:
            start=w['rune_offset'];end=start+len(w['values'])
            starts[start]=1;ends[end-1]=1
        cut=max(i+1 for i,yes in enumerate(ends) if yes and i+1<=int(.6*n))
        for trial in range(2):
            seed=330188+index*100+trial
            rng=random.Random(seed);key=[rng.randrange(29) for _ in range(13)]
            for kind in (['no_exceptions','selective_F'] if trial==0 else ['selective_F']):
                skipped=[];cipher=[];phase=0;f_ordinal=0
                for i,p in enumerate(plain):
                    skip=kind=='selective_F' and p==0 and f_ordinal%2==trial
                    if p==0:f_ordinal+=1
                    if skip:skipped.append(i);cipher.append(0)
                    else:cipher.append((p+key[phase])%29);phase=(phase+1)%13
                assert kind=='no_exceptions' or skipped
                cases.append({'id':f'{name}_{kind}_{trial}','source':name,'trial':trial,
                              'kind':kind,'construction_seed':seed,'decoder_seed':880000+index*100+trial*10+(kind=='selective_F'),
                              'cipher':cipher,'starts':starts,'ends':ends,'cut':cut,
                              'selective_F':kind=='selective_F','planted_key':key,
                              'planted_F_offsets':skipped,'gold_plaintext_sha256':digest(plain)})
        basis=next(c for c in cases if c['source']==name and c['kind']=='selective_F' and c['trial']==0)
        rng=random.Random(332188+index);left=basis['cipher'][:cut].copy();right=basis['cipher'][cut:].copy()
        rng.shuffle(left);rng.shuffle(right)
        cases.append({**basis,'id':f'{name}_shuffled','kind':'shuffled',
                      'decoder_seed':880000+index*100+50,'cipher':left+right,
                      'construction_seed':332188+index,'planted_key':None,
                      'planted_F_offsets':None,'gold_plaintext_sha256':None})
    return cases


def grade(case,answer,model,gold=None):
    if answer['status']!='completed':return answer
    key=answer['key'];cut=case['cut'];pre=answer['prefix'];post=answer['suffix']
    a=scalar(case['cipher'][:cut],case['starts'][:cut],case['ends'][:cut],key,set(pre['skips']),model,case['selective_F'])
    b=scalar(case['cipher'][cut:],case['starts'][cut:],case['ends'][cut:],key,set(post['skips']),model,case['selective_F'],pre['end_phase'])
    assert a[0]==pre['plaintext'] and a[1]==pre['end_phase'] and abs(a[2]-pre['score'])<1e-7
    assert b[0]==post['plaintext'] and b[1]==post['end_phase'] and abs(b[2]-post['score'])<1e-7
    output=a[0]+b[0]
    event_pre=cut+sum(case['ends'][:cut]);event_post=len(output)-cut+sum(case['ends'][cut:])
    out={k:v for k,v in answer.items() if k not in ['prefix','suffix']}
    out.update({'prefix_mean_score':pre['score']/event_pre,
                'continuation_mean_score':post['score']/event_post,
                'prefix_end_phase':pre['end_phase'],
                'prefix_skips':pre['skips'],'continuation_skips':[i+cut for i in post['skips']],
                'decoded_output_sha256':digest(output),'independent_scalar_reencryption':True,
                'key_and_prefix_state_frozen_before_continuation':True})
    if gold is not None:
        acc=lambda x,y:sum(a==b for a,b in zip(x,y))/len(y)
        out.update({'key_exact':key==case['planted_key'],
                    'prefix_rune_accuracy':acc(output[:cut],gold[:cut]),
                    'continuation_rune_accuracy':acc(output[cut:],gold[cut:]),
                    'full_rune_accuracy':acc(output,gold),
                    'full_output_exact':output==gold,
                    'skip_mask_exact':pre['skips']+[i+cut for i in post['skips']]==case['planted_F_offsets']})
    return out


def benchmark():
    fixtures_record=json.loads((ROOT/'recovery_benchmark_fixtures.json').read_text())
    assert fixtures_record['plan_sha256']==sha(PLAN)
    assert fixtures_record['driver_sha256']==sha(Path(__file__))
    assert fixtures_record['engine_source_sha256']==sha(ENGINE)
    compile_engine()
    refs,words,models=sources_and_models();cases=construct_cases(refs,words)
    dump('recovery_benchmark_cases.json',{'session':88,'cases':cases,
          'gold_reference':'increment_calibration_sources.json; not supplied to the decoder'})
    dump('recovery_benchmark_models.json',{'session':88,'models':{
        k:{'log':v['log'].tolist(),'unigram_log':v['unigram_log'].tolist(),
           'excluded_group':k,'training_groups':v['training_groups']} for k,v in models.items()}})
    rows=[]
    for case in cases:
        model=models[case['source']]
        answer=run_engine(case,model)
        result=grade(case,answer,model,None if case['kind']=='shuffled' else refs[case['source']])
        row={'id':case['id'],'source':case['source'],'kind':case['kind'],
             'runes':len(case['cipher']),'prefix_runes':case['cut'],
             'continuation_runes':len(case['cipher'])-case['cut'],'unknown_key':result}
        if case['kind']=='selective_F':
            oracle=run_engine(case,model,'oracle',case['planted_key'])
            row['supplied_key_path_diagnostic']=grade(case,oracle,model,refs[case['source']])
        rows.append(row)
        dump('recovery_benchmark_results.json',{'session':88,'complete':False,'rows':rows})
        print(case['id'],result['status'],
              {k:result[k] for k in ['key_exact','prefix_rune_accuracy','continuation_rune_accuracy'] if k in result},flush=True)
    positives=[r for r in rows if r['kind']!='shuffled']
    passed=all(r['unknown_key'].get('key_exact',False)
               and r['unknown_key'].get('prefix_rune_accuracy',0)>=.95
               and r['unknown_key'].get('continuation_rune_accuracy',0)>=.95 for r in positives)
    out={'session':88,'complete':True,'gate_passed':passed,'rows':rows,
         'plan_sha256':sha(PLAN),'fixtures_sha256':sha(ROOT/'recovery_benchmark_fixtures.json'),
         'cases_sha256':sha(ROOT/'recovery_benchmark_cases.json'),
         'models_sha256':sha(ROOT/'recovery_benchmark_models.json'),
         'driver_sha256':sha(Path(__file__)),'engine_sha256':sha(ENGINE),
         'source_hashes':{name:sha(ROOT/name) for name in ['lp_core.py','word_core.py','lexical_words.py',
                         'increment_calibration_sources.json','liber-primus__transcription--master.txt']},
         'no_unsolved_section_search':True,'no_new_plaintext':True}
    dump('recovery_benchmark_results.json',out)
    print('GATE',passed,flush=True)


if __name__=='__main__':
    parser=argparse.ArgumentParser();parser.add_argument('stage',choices=['fixtures','benchmark'])
    args=parser.parse_args()
    fixtures() if args.stage=='fixtures' else benchmark()
