"""Session 78: reversible repeat channel plus plaintext-driven running state.

Python + NumPy + matplotlib, local retained sources only.
Control gates precede the real-text screen. No seed dictionary or network.
"""
import json
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

from lp_core import ROOT, R, LET, pages, lp, vals, render
from word_core import FULL_MODEL, replace_values
from lexical_words import tokenize_words
from key_increment_audit import sha

PARAMETERS=np.array([(r,k) for r in range(29) for k in range(29)],dtype=np.int64)
ALLOWED={'AI':{24,10},'AIO':{24,10,3}}
RETAIN=3
EXEMPT={(6,75),(54,0)}


def encode(plain,reserved,initial):
    key=int(initial);previous=None;out=[]
    for symbol in plain:
        p=int(symbol)
        if previous is None:current=(p+key)%29
        else:
            trigger=(previous-key)%29
            current=previous if p==reserved else (reserved+key)%29 if p==trigger else (p+key)%29
            assert (current==previous)==(p==reserved)
        out.append(current);previous=current;key=(key+p*p)%29
    return np.array(out,dtype=np.int64)


def decode_many(cipher,parameters=PARAMETERS):
    parameters=np.asarray(parameters,dtype=np.int64)
    designated=parameters[:,0];key=parameters[:,1].copy()
    result=np.empty((len(parameters),len(cipher)),dtype=np.int64)
    previous=None
    for i,symbol in enumerate(cipher):
        current=int(symbol);p=(current-key)%29
        if previous is not None:
            if current==previous:p=designated.copy()
            else:p=np.where(p==designated,(previous-key)%29,p)
        result[:,i]=p;key=(key+p*p)%29;previous=current
    return result


def exhaustive_row_checks():
    key=np.arange(29)[:,None,None,None]
    previous=np.arange(29)[None,:,None,None]
    designated=np.arange(29)[None,None,:,None]
    p=np.arange(29)[None,None,None,:]
    trigger=(previous-key)%29
    cipher=np.where(p==designated,previous,
                    np.where(p==trigger,(designated+key)%29,(p+key)%29))
    assert np.all(np.sort(cipher,axis=-1)==p)
    candidate=(cipher-key)%29
    decoded=np.where(cipher==previous,designated,
                     np.where(candidate==designated,trigger,candidate))
    assert np.all(decoded==p)
    assert np.all((cipher==previous)==(p==designated))
    return {'state_contexts':29**3,'plaintext_cases':29**4,
            'all_rows_bijective':True,'all_inverses_exact':True,
            'repeat_identity_exact':True}


def target(source,identifier,global_start=0,words=None):
    words=tokenize_words(source) if words is None else words
    local=[{**w,'local_offset':w['rune_offset']-global_start} for w in words]
    cipher=vals(source)
    assert sum(len(w['values']) for w in local)==len(cipher)
    limit=min(256,int(.6*len(cipher)))
    cut=max(w['local_offset']+len(w['values']) for w in local
            if w['local_offset']+len(w['values'])<=limit)
    return {'id':identifier,'source':source,'cipher':cipher,'words':local,
            'cut':cut,'global_start':global_start}


def eligible_singletons(t,cut=None,real=False):
    return [w for w in t['words'] if len(w['values'])==1
            and (cut is None or w['local_offset']<cut)
            and not (real and (w['page'],w['page_rune_offset']) in EXEMPT)]


def word_score(values,words,start=0):
    lengths=[len(w['values']) for w in words]
    assert sum(lengths)==values.shape[1]
    return FULL_MODEL.score(values,lengths)


def prefix_screen(t,real=False):
    prefix=decode_many(t['cipher'][:t['cut']])
    words=[w for w in t['words'] if w['local_offset']+len(w['values'])<=t['cut']]
    scores=word_score(prefix,words)
    singles=eligible_singletons(t,t['cut'],real)
    offsets=[w['local_offset'] for w in singles]
    bad={name:np.count_nonzero(~np.isin(prefix[:,offsets],list(allowed)),axis=1)
         for name,allowed in ALLOWED.items()}
    return {'values':prefix,'scores':scores,'bad':bad,
            'units':t['cut']+len(words),'singleton_count':len(singles)}


def ranked(scores,bad):
    permitted=np.flatnonzero(bad==0)
    order=np.lexsort((PARAMETERS[permitted,1],PARAMETERS[permitted,0],-scores[permitted]))
    return permitted[order].tolist()


def reading(t,index,prefix,real=False,threshold=None):
    params=PARAMETERS[index]
    decoded=decode_many(t['cipher'],params[None,:])[0]
    assert np.array_equal(decoded[:t['cut']],prefix['values'][index])
    assert np.array_equal(encode(decoded,*map(int,params)),t['cipher'])
    following=[w for w in t['words'] if w['local_offset']>=t['cut']]
    score=float(word_score(decoded[None,t['cut']:],following)[0])
    singles=eligible_singletons(t,None,real)
    violations={name:[{'global_rune_offset':w['rune_offset'],
                       'page':w['page'],'page_rune_offset':w['page_rune_offset'],
                       'decoded_value':int(decoded[w['local_offset']])}
                      for w in singles if int(decoded[w['local_offset']]) not in allowed]
                for name,allowed in ALLOWED.items()}
    repeats=int(np.count_nonzero(t['cipher'][1:]==t['cipher'][:-1]))
    designated=int(np.count_nonzero(decoded[1:]==params[0]))
    assert repeats==designated
    return {'parameter_index':index,'reserved_rune':int(params[0]),
            'reserved_label':LET[int(params[0])],'initial_key':int(params[1]),
            'prefix_runes':t['cut'],'continuation_runes':len(decoded)-t['cut'],
            'prefix_score':float(prefix['scores'][index]),'continuation_score':score,
            'decoded_values':decoded.tolist(),'decoded_text_with_source_layout':render(t['source'],decoded),
            'full_singleton_violations':violations,'repeats':repeats,
            'designated_rune_count_after_initial':designated,
            'continuation_reference_screen':{name:(not violations[name] and score>=threshold)
                                              if threshold is not None else None
                                              for name in ALLOWED},
            'reencryption_matches':True,
            'reencryption_limit':'Expected for any decoded input under this bijection; not evidence for a real key.'}


def controls(plan):
    manifest=json.loads((ROOT/'increment_calibration_sources.json').read_text())
    known={g['name']:g['values'] for g in manifest['groups']}
    templates={'welcome':'%'.join(pages[1:3]),'second_koan':'%'.join(pages[12:14])}
    rows=[]
    for name in plan['controls']['sources']:
        plaintext=np.array(known[name],dtype=np.int64)
        for reserved,initial in plan['controls']['planted_pairs']:
            ciphertext=encode(plaintext,reserved,initial)
            decoded=decode_many(ciphertext,np.array([[reserved,initial]]))[0]
            assert np.array_equal(decoded,plaintext)
            source=replace_values(templates[name],ciphertext)
            t=target(source,name);prefix=prefix_screen(t)
            order=ranked(prefix['scores'],prefix['bad']['AI'])
            planted=reserved*29+initial
            selected=order[:RETAIN]
            correct=reading(t,planted,prefix)
            assert np.array_equal(correct['decoded_values'],plaintext)
            equal_score=np.flatnonzero((prefix['bad']['AI']==0)&
                                      np.isclose(prefix['scores'],prefix['scores'][planted],atol=1e-12,rtol=0))
            row={'source':name,'planted_pair':[reserved,initial],
                 'ciphertext_values':ciphertext.tolist(),
                 'known_key_roundtrip_exact':True,
                 'prefix_eligible_candidates':len(order),
                 'planted_prefix_rank':order.index(planted)+1 if planted in order else None,
                 'prefix_score_tied_parameter_indices':equal_score.tolist(),
                 'all_841_prefix_scores':prefix['scores'].tolist(),
                 'all_841_AI_violation_counts':prefix['bad']['AI'].tolist(),
                 'all_841_AIO_violation_counts':prefix['bad']['AIO'].tolist(),
                 'retained_parameter_indices':selected,
                 'planted_retained':planted in selected,
                 'retained_planted_full_plaintext_exact':True,
                 'correct_reading':correct,
                 'gate_passed':planted in selected}
            rows.append(row)
            print(json.dumps({'control':name,'pair':[reserved,initial],
                              'prefix_rank':row['planted_prefix_rank'],
                              'gate':row['gate_passed']}),flush=True)
    assert len(rows)==6
    return {'rows':rows,'all_six_gates_passed':all(r['gate_passed'] for r in rows),
            'lowest_correct_continuation_score':min(r['correct_reading']['continuation_score'] for r in rows),
            'training_excludes_both_control_sources':True,
            'retention_limit':RETAIN}


def real_targets():
    source='%'.join(lp[:56]);words=tokenize_words(source)
    targets=[];start=0
    for section,piece in enumerate(source.split('$')):
        size=len(vals(piece))
        if size>100:
            t=target(piece,section,start,[w for w in words if w['section']==section])
            targets.append(t)
        start+=size
    assert [t['id'] for t in targets]==[0,1,2,4,5,6,7,8]
    assert sum(len(t['cipher']) for t in targets)==12947
    assert sum(len(eligible_singletons(t,None,True)) for t in targets)==81
    return targets


def screen_real(threshold):
    targets=real_targets();prefixes={t['id']:prefix_screen(t,True) for t in targets}
    rows=[]
    for t in targets:
        screen=prefixes[t['id']];branches={};selected=set()
        for name in ALLOWED:
            order=ranked(screen['scores'],screen['bad'][name]);retain=order[:RETAIN]
            selected.update(retain)
            branches[name]={'passing_prefix_pairs':len(order),
                            'minimum_prefix_singleton_violations':int(screen['bad'][name].min()),
                            'retained_parameter_indices':retain}
        readings=[reading(t,i,screen,True,threshold) for i in sorted(selected)]
        rows.append({'section':t['id'],'runes':len(t['cipher']),
                     'global_start':t['global_start'],'prefix_runes':t['cut'],
                     'prefix_eligible_singletons':screen['singleton_count'],
                     'branches':branches,'readings':readings,
                     'all_prefix_candidates':[{'parameter_index':i,'R':int(r),'initial_K':int(k),
                        'score':float(screen['scores'][i]),
                        'AI_violations':int(screen['bad']['AI'][i]),
                        'AIO_violations':int(screen['bad']['AIO'][i])}
                        for i,(r,k) in enumerate(PARAMETERS)]})
    weighted=sum(prefixes[i]['scores']*prefixes[i]['units'] for i in [0,1,2,4])
    weighted/=sum(prefixes[i]['units'] for i in [0,1,2,4])
    shared={}
    for name in ALLOWED:
        bad=sum(prefixes[i]['bad'][name] for i in [0,1,2,4])
        order=ranked(weighted,bad);retained=order[:RETAIN]
        shared[name]={'passing_pairs':len(order),'minimum_prefix_singleton_violations':int(bad.min()),
                      'eligible_training_singletons':sum(prefixes[i]['singleton_count'] for i in [0,1,2,4]),
                      'retained_parameter_indices':retained,
                      'all_841_scores':weighted.tolist(),'all_841_violation_counts':bad.tolist(),
                      'frozen_readings':[{'parameter_index':i,
                                         'sections':[reading(t,i,prefixes[t['id']],True,threshold) for t in targets]}
                                        for i in retained]}
    return {'scope':'Eight substantial sections; section-local and shared-pair branches are separate declared comparisons.',
            'continuation_score_reference':threshold,'section_local_rows':rows,
            'shared_pair_first_four_prefixes':shared,
            'limits':'Later-section prefix choices in the local sensitivity are local fits, not transfer of a global key. All continuation choices retain their prefix parameters.'}


def plot_scores(controls_result,real):
    fig,ax=plt.subplots(figsize=(9,6),layout='constrained')
    cc=[r['correct_reading'] for r in controls_result['rows']]
    ax.scatter([r['prefix_score'] for r in cc],[r['continuation_score'] for r in cc],
               label='Correct planted controls',c='#286fa8',s=75,marker='s')
    if real is not None:
        candidates=[r for section in real['section_local_rows'] for r in section['readings']]
        ax.scatter([r['prefix_score'] for r in candidates],[r['continuation_score'] for r in candidates],
                   label='Section-local selected real candidates',c='#be6b2c',s=35,alpha=.75)
    ax.axhline(controls_result['lowest_correct_continuation_score'],c='#9b2335',ls='--',
               label='Lowest correct-control continuation')
    ax.set_xlabel('Prefix word-model score');ax.set_ylabel('Continuation word-model score')
    ax.set_title('Plaintext-driven square state and reversible repeat channel')
    ax.grid(alpha=.2);ax.legend(fontsize=9)
    fig.savefig(ROOT/'plaintext_swap_scores.png',dpi=150);plt.close(fig)


def main():
    plan=json.loads((ROOT/'plaintext_swap_plan.json').read_text())
    algebra=exhaustive_row_checks()
    control_result=controls(plan)
    # Save and hash completed control results before any real decoding.
    control_path=ROOT/'plaintext_swap_controls.json'
    control_payload={'session':78,'exhaustive_algebra':algebra,**control_result,
                     'source_hashes':{n:sha(ROOT/n) for n in [
                         'plaintext_swap_plan.json','plaintext_swap_audit.py',
                         'increment_calibration_sources.json','lp_core.py','word_core.py','lexical_words.py']}}
    control_path.write_text(json.dumps(control_payload,indent=2)+'\n')
    real=screen_real(control_result['lowest_correct_continuation_score']) if control_result['all_six_gates_passed'] else None
    result={'session':78,'parameters':PARAMETERS.tolist(),
            'control_file_sha256_before_real_run':sha(control_path),
            'real_run_permitted':control_result['all_six_gates_passed'],
            'real':real,'limits':plan['limits'],
            'source_hashes':{n:sha(ROOT/n) for n in [
                'plaintext_swap_plan.json','plaintext_swap_audit.py','plaintext_swap_controls.json',
                'liber-primus__transcription--master.txt','increment_calibration_sources.json',
                'lp_core.py','word_core.py','lexical_words.py']}}
    path=ROOT/'plaintext_swap_results.json'
    path.write_text(json.dumps(result,indent=2)+'\n')
    plot_scores(control_result,real)
    summary={'control_gate':control_result['all_six_gates_passed'],
             'control_suffix_floor':control_result['lowest_correct_continuation_score'],
             'real_run':real is not None,'result_sha256':sha(path)}
    if real is not None:
        summary['shared']={k:{'passing_pairs':v['passing_pairs'],
                              'minimum_violations':v['minimum_prefix_singleton_violations']}
                           for k,v in real['shared_pair_first_four_prefixes'].items()}
        summary['sections']=[{'section':row['section'],'prefix_pairs':{k:v['passing_prefix_pairs'] for k,v in row['branches'].items()},
                              'selected_readings':len(row['readings']),
                              'continuation_reference_passes':{name:sum(r['continuation_reference_screen'][name]
                                    for r in row['readings'] if r['parameter_index'] in row['branches'][name]['retained_parameter_indices'])
                                    for name in ALLOWED}} for row in real['section_local_rows']]
    print(json.dumps(summary,indent=2),flush=True)


if __name__=='__main__':main()
