"""Session 91: fixed first-section experiment, 99 nulls then one original fit.

No retuning, seed retries or continuation-based key selection. Historical
companions are read only. Run prepare, checks and benchmark in that order.
"""
from collections import Counter
from pathlib import Path
import argparse
import hashlib
import json
import platform
import random
import statistics

import numpy as np
import recovery_benchmark as base
import rotation_recovery as recovery
from lexical_words import tokenize_words
from lp_core import lp, vals, LET, R

ROOT=base.ROOT
PLAN=ROOT/'first_section_recovery_next_plan.json'
CASES=ROOT/'first_section_cases.json'
MODEL=ROOT/'first_section_model.json'
SPEC=ROOT/'first_section_execution.json'
CHECKS=ROOT/'first_section_checks.json'
RESULTS=ROOT/'first_section_results.json'
INPUTS=['first_section_recovery_next_plan.json','rotation_recovery.py',
        'recovery_benchmark.py','rotation_recovery_engine.cpp',
        'rotation_recovery_execution.json','rotation_recovery_fixtures.json',
        'recovery_benchmark_models.json','lp_core.py','word_core.py','lexical_words.py',
        'increment_calibration_sources.json','liber-primus__transcription--master.txt']


def read(path):return json.loads(path.read_text())


def train(refs,words,exclude=None):
    uni=np.ones(30)*.5;bc=np.zeros((30,30));tc=np.zeros((30,30,30));groups=[]
    for name,plain in refs.items():
        if name==exclude:continue
        groups.append(name)
        for word in words[name]:
            start=word['rune_offset'];p=plain[start:start+len(word['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)
    return {'log':np.log(tp),'unigram_log':np.log(up[:29]/up[:29].sum()),'training_groups':groups}


def prepare():
    assert not RESULTS.exists(),'Preserve recorded fits; reproduce on a separate copy.'
    plan=read(PLAN);recovery.verify_spec()
    assert base.sha(ROOT/plan['source']['master_file'])==plan['source']['master_sha256']
    assert base.sha(ROOT/'increment_calibration_sources.json')==plan['model']['training_manifest_sha256']
    refs,training_words,_=base.sources_and_models()
    assert len(refs)==9 and sum(map(len,refs.values()))==2977
    model=train(refs,training_words)
    base.dump(MODEL.name,{'session':91,'log':model['log'].tolist(),
              'unigram_log':model['unigram_log'].tolist(),'training_groups':model['training_groups'],
              'group_rune_counts':{k:len(v) for k,v in refs.items()},'total_training_runes':2977,
              'formula':'Session 88 formula, all nine retained solved groups; no unsolved training.'})
    source='%'.join(lp[:56]).split('$')[0];cipher=vals(source).tolist();words=tokenize_words(source)
    n=len(cipher);starts=[0]*n;ends=[0]*n
    for word in words:
        start=word['rune_offset'];end=start+len(word['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))
    assert (n,len(words),sum(len(w['values'])==1 for w in words),cut,n-cut)==(729,158,5,437,292)
    common={'source':'marked_section_0','starts':starts,'ends':ends,'cut':cut,
            'selective_F':True,'decoder_seed':910000}
    cases=[];seen={};duplicates=[];identities=[]
    for replicate in range(99):
        seed=330191+replicate;rng=random.Random(seed)
        left=cipher[:cut].copy();right=cipher[cut:].copy();rng.shuffle(left);rng.shuffle(right)
        shuffled=left+right;identity=f'null_{replicate:02d}';signature=base.digest(shuffled)
        prior=seen.get(signature)
        if prior:duplicates.append({'id':identity,'same_ciphertext_as':prior})
        else:seen[signature]=identity
        if shuffled==cipher:identities.append(identity)
        cases.append({**common,'id':identity,'kind':'null','replicate':replicate,
                      'construction_seed':seed,'cipher':shuffled,'duplicate_of':prior,
                      'cipher_sha256':signature})
    cases.append({**common,'id':'original','kind':'original','cipher':cipher,
                  'cipher_sha256':base.digest(cipher)})
    base.dump(CASES.name,{'session':91,'section':0,'runes':n,'source_text':source,
              'words':[{k:w[k] for k in ['word_index','page','page_rune_offset','rune_offset']}|{'length':len(w['values'])} for w in words],
              'cases':cases,'null_duplicates':duplicates,'null_identity_cases':identities,
              'no_redraws':True,'no_plaintext_reference_or_planted_key':True})
    base.dump(SPEC.name,{'session':91,'saved_before_any_null_or_original_fit':True,
              'driver_sha256':base.sha(Path(__file__)),'model_sha256':base.sha(MODEL),
              'cases_sha256':base.sha(CASES),'input_hashes':{n:base.sha(ROOT/n) for n in INPUTS},
              'extracted_source_sha256':hashlib.sha256(source.encode()).hexdigest(),
              'execution_order':'Nulls 0..98, then original exactly once, in one fixed script.',
              'search':'Unchanged Session 89 fit_rotations; 8 restarts, 6 sweeps maximum, 13 slots; seed 910000 for every fit; 120 seconds per process.',
              'score_rule':plan['predeclared_candidate_screen']['scores'],
              'singleton_rule':plan['predeclared_candidate_screen']['words'],
              'rank_rule':'1 + count of completed null scores >= original score, separately for prefix and continuation. Descriptive, not calibrated p-values.',
              'stop_rule':plan['stopping_rule'],'python':platform.python_version(),
              'no_other_unsolved_section_fit':True})
    print('PREPARED all-nine-group model, 99 nulls, one original; duplicates',len(duplicates),'identity',len(identities),flush=True)


def verify():
    spec=read(SPEC)
    assert spec['driver_sha256']==base.sha(Path(__file__))
    assert spec['model_sha256']==base.sha(MODEL) and spec['cases_sha256']==base.sha(CASES)
    for name,sha in spec['input_hashes'].items():assert base.sha(ROOT/name)==sha,name


def checks():
    verify();recovery.verify_spec();snapshot=read(CASES);cases=snapshot['cases'];original=cases[-1]
    assert len(cases)==100 and original['kind']=='original' and original['id']=='original'
    assert [c['replicate'] for c in cases[:-1]]==list(range(99))
    source='%'.join(lp[:56]).split('$')[0];cipher=vals(source).tolist();words=tokenize_words(source)
    assert snapshot['source_text']==source and original['cipher']==cipher
    assert len(cipher)==729 and len(words)==158 and sum(w['length']==1 for w in snapshot['words'])==5
    for word in words:
        start=word['rune_offset'];end=start+len(word['values'])
        assert original['starts'][start] and original['ends'][end-1]
    assert sum(original['starts'])==sum(original['ends'])==158
    for c in cases:
        cut=c['cut'];assert cut==437 and len(c['cipher'])-cut==292 and c['ends'][cut-1]
        assert c['starts']==original['starts'] and c['ends']==original['ends']
        assert c['decoder_seed']==910000 and c['selective_F']
        assert Counter(c['cipher'][:cut])==Counter(cipher[:cut])
        assert Counter(c['cipher'][cut:])==Counter(cipher[cut:])
        assert base.digest(c['cipher'])==c['cipher_sha256']
        if c['kind']=='null':
            assert c['construction_seed']==330191+c['replicate']
            rng=random.Random(c['construction_seed']);left=cipher[:cut].copy();right=cipher[cut:].copy()
            rng.shuffle(left);rng.shuffle(right);assert c['cipher']==left+right
        assert not any(k in c for k in ['planted_key','gold_plaintext','planted_F_offsets'])
    refs,training_words,_=base.sources_and_models();frozen=recovery.load_models();parity=[]
    for target in base.TARGETS:
        m=train(refs,training_words,target)
        assert np.array_equal(m['log'],frozen[target]['log'])
        assert np.array_equal(m['unigram_log'],frozen[target]['unigram_log'])
        assert m['training_groups']==frozen[target]['training_groups'];parity.append(target)
    pooled=train(refs,training_words);saved=read(MODEL)
    assert saved['total_training_runes']==2977 and len(saved['training_groups'])==9
    assert np.array_equal(pooled['log'],saved['log']) and np.array_equal(pooled['unigram_log'],saved['unigram_log'])
    assert np.allclose(np.exp(pooled['log']).sum(axis=2),1,rtol=0,atol=1e-12)
    assert abs(np.exp(pooled['unigram_log']).sum()-1)<1e-12
    fixtures=read(ROOT/'rotation_recovery_fixtures.json')
    assert fixtures['passed'] and fixtures['execution_sha256']==base.sha(ROOT/'rotation_recovery_execution.json')
    base.dump(CHECKS.name,{'session':91,'passed':True,'execution_sha256':base.sha(SPEC),
              'source_and_layout_verified':True,'case_constructions_verified':100,
              'training_formula_matches_all_four_frozen_excluded_models':parity,
              'all_nine_group_snapshot_and_probability_checks':True,
              'retained_decoder_fixture_hash_verified':True,'no_extra_decoder_fits':True})
    print('CHECKS PASS: 100 inputs, 4 training parities, pooled model, retained decoder fixtures',flush=True)


def summarize(rows,words):
    nulls=[r['fit'] for r in rows if r['kind']=='null' and r['fit']['status']=='completed']
    original=next(r['fit'] for r in rows if r['kind']=='original')
    out={'completed_nulls':len(nulls),'unresolved_nulls':99-len(nulls),
         'original_status':original['status'],'candidate_screen':'unresolved'}
    for label,field in [('prefix','prefix_mean_score'),('continuation','continuation_mean_score')]:
        scores=[r[field] for r in nulls]
        out[label+'_null']={'minimum':min(scores),'median':statistics.median(scores),'maximum':max(scores)} if scores else None
        if original['status']=='completed' and scores:
            score=original[field]
            out[label+'_original_score']=score
            out[label+'_margin_above_null_max']=score-max(scores)
            out[label+'_null_ge_count']=sum(s>=score for s in scores)
            out[label+'_rank']=1+sum(s>=score for s in scores)
            out[label+'_strict_score_check']=score>max(scores)
    if original['status']=='completed':
        values=original['literal_plaintext_values'];singletons=[]
        for word in words:
            if word['length']==1:
                p=values[word['rune_offset']]
                singletons.append({**word,'returned_value':p,'returned_label':LET[p],
                                   'allowed_A_I_O':p in [24,10,3]})
        out['singletons']=singletons
        out['singletons_passed']=sum(w['allowed_A_I_O'] for w in singletons)
        out['all_singletons_passed']=all(w['allowed_A_I_O'] for w in singletons)
        out['joint_null_ge_count']=sum(r['prefix_mean_score']>=original['prefix_mean_score'] and r['continuation_mean_score']>=original['continuation_mean_score'] for r in nulls)
        if len(nulls)==99:
            out['candidate_screen']='passed' if out['prefix_strict_score_check'] and out['continuation_strict_score_check'] and out['all_singletons_passed'] else 'failed'
    return out


def write_reading(case,answer,words):
    values=answer['literal_plaintext_values'];cut=case['cut']
    before=[];after=[];table=[]
    for word in words:
        start=word['rune_offset'];p=values[start:start+word['length']]
        transliteration=''.join(LET[v] for v in p)
        (before if start<cut else after).append(transliteration)
        table.append(f"{word['word_index']:03d}\t{start:03d}\t{word['length']}\t{''.join(R[v] for v in p)}\t{' '.join(LET[v] for v in p)}")
    text='Session 91 returned fit, NOT a verified decryption. No hand corrections.\n'
    text+='Rune-label expansions joined inside the supplied lexical words.\n\nSELECTION PREFIX (437 runes)\n'+' '.join(before)
    text+='\n\nFROZEN-KEY CONTINUATION (292 runes)\n'+' '.join(after)
    text+='\n\nExact per-word output: word_index\trune_offset\tlength\trunes\trune labels\n'+'\n'.join(table)+'\n'
    (ROOT/'first_section_literal_output.txt').write_text(text)


def benchmark():
    verify();check=read(CHECKS);assert check['passed'] and check['execution_sha256']==base.sha(SPEC)
    assert not RESULTS.exists(),'Do not overwrite or retry recorded fits.'
    recovery.compile_engine();saved=read(MODEL)
    model={'log':np.asarray(saved['log']),'unigram_log':np.asarray(saved['unigram_log'])}
    snapshot=read(CASES);rows=[]
    for c in snapshot['cases']:
        raw=recovery.run(c,model,'fit_rotations');answer=base.grade(c,raw,model)
        if answer['status']=='completed':
            answer['literal_plaintext_values']=raw['prefix']['plaintext']+raw['suffix']['plaintext']
            assert base.digest(answer['literal_plaintext_values'])==answer['decoded_output_sha256']
        rows.append({'id':c['id'],'kind':c['kind'],'fit':answer})
        base.dump(RESULTS.name,{'session':91,'complete':False,'execution_sha256':base.sha(SPEC),'rows':rows})
        if len(rows)%11==0 or c['kind']=='original':print('RECORDED',len(rows),'/100',c['id'],answer['status'],flush=True)
    verify();summary=summarize(rows,snapshot['words'])
    base.dump(RESULTS.name,{'session':91,'complete':True,'execution_sha256':base.sha(SPEC),
              'checks_sha256':base.sha(CHECKS),'rows':rows,'summary':summary,
              'only_one_original_fit':True,'no_other_unsolved_section_fit':True,
              'no_verified_new_plaintext':True,'ranks_are_not_calibrated_p_values':True})
    original=rows[-1]['fit']
    if original['status']=='completed':write_reading(snapshot['cases'][-1],original,snapshot['words'])
    print('COMPLETE',json.dumps(summary),flush=True)


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