"""Session 76: fixed-length additive encoder controls for the prior diagnostic.

Python, NumPy, SciPy and matplotlib. Run beside retained companion files.
All trial keys are generated independently of the known plaintext.
This is a conditional model comparison, not an omnibus cipher rejection.
"""
import json
from pathlib import Path

import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

from lp_core import ROOT, R, LET, pages, lp, vals, SEQS
from word_core import GROUPS
from key_increment_audit import differences, prob, convolution_matrix, best_fit, sha

B = 29
PLAN = ROOT/'increment_calibration_plan.json'


def letters(v):
    return ''.join(LET[int(x)] for x in v)


def translation_prefix(prefix):
    text = ' '.join(line.split('\t')[-1].strip()
                    for line in (ROOT/'liber-primus__translation.txt').read_text().splitlines()
                    if any(line.startswith(p) for p in prefix))
    return ''.join(ch for ch in text.upper().translate(
        str.maketrans({'C':'K', 'Q':'K', 'V':'U', 'Z':'S'})) if ch.isalpha())


def known_decode(source, key_function, skip_offsets):
    ciphertext = vals(source)
    plaintext = np.empty_like(ciphertext)
    effective_key = np.empty_like(ciphertext)
    counter = 0
    for i, cipher in enumerate(ciphertext):
        if i in skip_offsets:
            assert cipher == 0
            key = 0
        else:
            key = key_function(counter)
            counter += 1
        effective_key[i] = key
        plaintext[i] = (cipher-key) % B
    assert np.array_equal((plaintext+effective_key) % B, ciphertext)
    return plaintext, ciphertext, effective_key


def known_sources(plan):
    rules = plan['known_decode_rules']
    key = vals(rules['welcome_key'])
    welcome, welcome_c, welcome_k = known_decode(
        '%'.join(pages[1:3]), lambda i:int(key[i % len(key)]),
        set(rules['welcome_unenciphered_F_offsets']))
    literal = letters(welcome)
    compared = literal.replace('ALOINGTHEWAY','ALONGTHEWAY').replace('WIDSOM','WISDOM')
    assert compared == translation_prefix(['0.1.0.', '0.1.1.'])
    assert literal.count('ALOINGTHEWAY') == literal.count('WIDSOM') == 1

    key = vals(rules['second_koan_key'])
    second, second_c, second_k = known_decode(
        '%'.join(pages[12:14]), lambda i:int(key[i % len(key)]),
        set(rules['second_koan_unenciphered_F_offsets']))
    assert letters(second) == translation_prefix(['0.4.0.'])

    end_source = lp[56]
    end, end_c, end_k = known_decode(end_source,
        lambda i:int(SEQS['prime_minus_one'][i]), {56})
    retained = json.loads((ROOT/'solved_punctuation_results.json').read_text())
    reference = next(r['plaintext_with_source_delimiters']
                     for r in retained['records'] if r['file'] == '73.jpg')
    iterator = iter(end)
    rendered = ''.join(LET[int(next(iterator))] if ch in R else ch for ch in end_source)
    assert rendered == reference

    old = {name:vals(source) for name, source in GROUPS.items()}
    # Original book order rather than appending all additions at the end.
    expanded = {'warning':old['warning'], 'welcome':welcome,
                'wisdom':old['wisdom'], 'koan':old['koan'],
                'divinity':old['divinity'], 'second_koan':second,
                'instruction':old['instruction'], 'lp2_56':end,
                'lp2_57':vals(lp[57])}
    assert sum(map(len, expanded.values())) == 2977
    baselines = []
    for name, plaintext, ciphertext, key_values in [
        ('welcome', welcome, welcome_c, welcome_k),
        ('second_koan', second, second_c, second_k),
        ('lp2_56', end, end_c, end_k)]:
        fitted = best_fit(prob(differences(plaintext)), prob(differences(ciphertext)))
        baselines.append({'name':name, 'runes':len(plaintext),
                          'plaintext_values':plaintext.tolist(),
                          'ciphertext_values':ciphertext.tolist(),
                          'effective_key_values':key_values.tolist(),
                          'known_reference_check_passed':True,
                          'exact_reencryption':True,
                          'minimum_tv_with_own_plaintext_profile':
                              fitted['minimum_total_variation'],
                          'interpretation':'A deterministic known key with selective F exceptions. Not a draw from the declared iid calibration models.'})
    sources = {'groups':[{'name':name,'runes':len(v),'values':v.tolist()}
                        for name,v in expanded.items()],
               'literal_runes':2977,
               'reference_transitions':2968,
               'welcome_comparison_only_normalizations':[
                   ['ALOINGTHEWAY','ALONGTHEWAY'], ['WIDSOM','WISDOM']],
               'literal_plaintext_unchanged':True,
               'known_enciphered_baselines':baselines,
               'primary_solver_reference':'https://github.com/scream314/cicada3301/blob/master/liber_primus.md',
               'input_hashes':{name:sha(ROOT/name) for name in [
                   'liber-primus__transcription--master.txt',
                   'liber-primus__translation.txt','solved_punctuation_results.json',
                   'boundary_model_audit.py','lp_core.py','word_core.py']}}
    return old, expanded, sources


def histogram(streams):
    return sum(differences(v) for v in streams)


def constructed_book(sources, lengths):
    cycle = np.concatenate(list(sources.values()))
    long = np.resize(cycle, sum(lengths))
    cut = np.cumsum(lengths)[:-1]
    return list(np.split(long, cut))


def draw_increments(rng, size, q, persistent):
    if not persistent:
        return rng.choice(B, size=size, p=q)
    # Refreshes form independent geometric-length runs. Start from q so every
    # position has marginal q; plaintext does not enter this generation.
    refresh = np.r_[True, rng.random(size-1) >= .95]
    starts = np.flatnonzero(refresh)
    values = rng.choice(B, size=len(starts), p=q)
    return np.repeat(values, np.diff(np.r_[starts,size]))


def fit_distance(p, target):
    return best_fit(p, target)['minimum_total_variation']


def summarize(values, observed=None):
    a=np.array(values)
    out={'mean':float(a.mean()), 'median':float(np.median(a)),
         'central_95_percent':np.quantile(a,[.025,.975]).tolist(),
         'minimum':float(a.min()), 'maximum':float(a.max()),
         'values':a.tolist()}
    if observed is not None:
        count=int(np.count_nonzero(a >= observed))
        out.update({'observed_comparison':float(observed),
                    'at_or_above_observed':count,
                    'conditional_trial_fraction':count/len(a),
                    'plus_one_comparison':(count+1)/(len(a)+1),
                    'interpretation':'Conditional simulation frequency under this constructed plaintext and selected key model. Not a calibrated composite-null p-value.'})
    return out


def plot_summary(rows, observed):
    fig, axes=plt.subplots(2,1,figsize=(11,8),sharey=True,layout='constrained')
    labels=['Uniform iid','Sparse iid','Fitted iid','Fitted persistent']
    for ax,book in zip(axes,['old','expanded']):
        selected=[r for r in rows if r['book']==book]
        base=np.arange(1,5)
        for shift,key,color,label in [(-.17,'actual_plaintext_profile','#286fa8','Actual constructed plaintext'),
                                     (.17,'old_reference','#be6b2c','Short original reference')]:
            data=[np.array(r['statistics'][key]['values'])*100 for r in selected]
            boxes=ax.boxplot(data,positions=base+shift,widths=.27,showfliers=False,
                             whis=[2.5,97.5],patch_artist=True)
            for patch in boxes['boxes']:patch.set_facecolor(color);patch.set_alpha(.7)
            ax.plot([],[],color=color,lw=7,label=label)
        ax.axhline(observed*100,color='#9b2335',ls='--',label='Real / original reference')
        ax.set_xticks(base,labels);ax.set_ylabel('Minimum total variation (%)')
        ax.set_title(f'{book.title()} source book: known prose cycled to 12,947 runes')
        ax.grid(axis='y',alpha=.2)
    axes[0].legend(loc='upper left',fontsize=9)
    fig.suptitle('Matched-length encoder controls: reference choice and key dependence',fontsize=14)
    fig.savefig(ROOT/'increment_calibration_summary.png',dpi=150)
    plt.close(fig)


def main():
    plan=json.loads(PLAN.read_text())
    old,expanded,sources=known_sources(plan)
    source_path=ROOT/'increment_calibration_sources.json'
    source_path.write_text(json.dumps(sources,indent=2,ensure_ascii=False)+'\n')
    old_p=prob(histogram(old.values()))
    expanded_p=prob(histogram(expanded.values()))
    prior=json.loads((ROOT/'key_increment_results.json').read_text())
    real=np.array(prior['real_corpus']['all']['increment_probabilities'])
    real_old=fit_distance(old_p,real)
    real_expanded_fit=best_fit(expanded_p,real)
    real_expanded=real_expanded_fit['minimum_total_variation']
    saved=next(r for r in prior['references'] if r['name']=='pooled')
    assert abs(real_old-saved['all_sections_best_fit']['minimum_total_variation']) < 1e-12
    fitted_q=np.array(saved['all_sections_best_fit']['key_increment_probabilities'])
    q_uniform=np.full(B,1/B)
    q_sparse=np.zeros(B);q_sparse[[0,4,17]]=[.2,.3,.5]
    models=[('uniform_iid',q_uniform,False),('sparse_iid',q_sparse,False),
            ('fitted_iid',fitted_q,False),('fitted_persistent',fitted_q,True)]
    lengths=[s['runes'] for s in prior['independent_section_sensitivity']['sections']]
    assert sum(lengths)==12947 and sum(n-1 for n in lengths)==12939
    rows=[]
    for book_id,(name,reference) in enumerate([('old',old),('expanded',expanded)]):
        streams=constructed_book(reference,lengths)
        actual=prob(histogram(streams))
        for model_id,(model,q,persistent) in enumerate(models):
            seed=int(plan['seed'])+book_id*100+model_id
            rng=np.random.default_rng(seed)
            scores={'actual_plaintext_profile':[], 'old_reference':[],
                    'expanded_reference':[], 'repeat_count':[]}
            expected=convolution_matrix(actual) @ q
            for trial in range(int(plan['trials_per_book_model'])):
                count=np.zeros(B,dtype=np.int64)
                for plaintext in streams:
                    increments=draw_increments(rng,len(plaintext)-1,q,persistent)
                    key=np.r_[7,7+np.cumsum(increments)] % B
                    ciphertext=(plaintext+key) % B
                    assert np.array_equal((ciphertext-key) % B,plaintext)
                    assert np.array_equal(np.diff(key)%B,increments)
                    count+=differences(ciphertext)
                observed=prob(count)
                for field,p in [('actual_plaintext_profile',actual),
                                ('old_reference',old_p),('expanded_reference',expanded_p)]:
                    scores[field].append(fit_distance(p,observed))
                scores['repeat_count'].append(int(count[0]))
            row={'book':name,'model':model,'seed':seed,
                 'trials':int(plan['trials_per_book_model']),
                 'exact_known_key_recoveries':int(plan['trials_per_book_model']),
                 'section_lengths':lengths,
                 'actual_plaintext_increment_probabilities':actual.tolist(),
                 'key_increment_probabilities':q.tolist(),
                 'expected_cipher_increment_probabilities':expected.tolist(),
                 'expected_repeat_count':float(expected[0]*12939),
                 'true_expected_distance_under_old_reference':fit_distance(old_p,expected),
                 'true_expected_distance_under_expanded_reference':fit_distance(expanded_p,expected),
                 'statistics':{field:summarize(data,
                    real_expanded if field=='expanded_reference' else
                    86 if field=='repeat_count' else real_old)
                    for field,data in scores.items()}}
            # The real book's true plaintext profile is unknown. Its reference
            # score is only a scale marker for the actual-profile control.
            row['statistics']['actual_plaintext_profile']['interpretation']=(
                'Real old-reference distance is a scale marker only; unknown true-profile distance is unavailable.')
            rows.append(row)
            print(json.dumps({'completed':name+'/'+model,
                              'true_profile_band':row['statistics']['actual_plaintext_profile']['central_95_percent'],
                              'old_reference_band':row['statistics']['old_reference']['central_95_percent'],
                              'old_reference_at_or_above':row['statistics']['old_reference']['at_or_above_observed']},indent=None),flush=True)
    result={'session':76,'trials':len(rows)*int(plan['trials_per_book_model']),
            'known_key_recovery':'Exact for every generated book; does not establish unknown-key recovery.',
            'real_old_reference_distance':real_old,
            'real_expanded_reference_fit':real_expanded_fit,
            'short_reference_profiles':{'old':old_p.tolist(),'expanded':expanded_p.tolist()},
            'constructed_book_profiles':'Measured from cycled source strings with artificial joins and retained section boundaries.',
            'rows':rows, 'limits':plan['limits'],
            'source_hashes':{name:sha(ROOT/name) for name in [
                'increment_calibration.py','increment_calibration_plan.json',
                'increment_calibration_sources.json','key_increment_audit.py',
                'key_increment_results.json','liber-primus__transcription--master.txt',
                'liber-primus__translation.txt','lp_core.py','word_core.py',
                'solved_punctuation_results.json']}}
    path=ROOT/'increment_calibration_results.json'
    path.write_text(json.dumps(result,indent=2)+'\n')
    plot_summary(rows,real_old)
    print(json.dumps({'done':True,'trials':result['trials'],
                      'old_real_distance':real_old,'expanded_real_distance':real_expanded,
                      'result_sha256':sha(path)},indent=2),flush=True)


if __name__=='__main__':main()
