"""Session 89: paired ordinary/rotation search on the frozen control set.

No unsolved-text search. Preserve Session 88 code and evidence byte for byte.
Run `prepare`, then `fixtures`, then `benchmark`, then `regressions`.
"""
from pathlib import Path
import argparse
import json
import math
import random
import subprocess

import numpy as np
import recovery_benchmark as old

ROOT = old.ROOT
PLAN = ROOT/'rotation_recovery_next_plan.json'
SPEC = ROOT/'rotation_recovery_execution.json'
ENGINE = ROOT/'rotation_recovery_engine.cpp'
BINARY = ROOT.parents[1]/'.sites-runtime/rotation-recovery-engine'
METHODS = {'ordinary':'fit', 'rotations':'fit_rotations'}


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(case,model,mode='fit',key=None,phase=0):
    # Reuse unchanged serialization and timeout handling, with the new binary.
    # Only supplied-key diagnostics/probes append K. Fit never receives gold.
    previous=old.BINARY
    old.BINARY=BINARY
    try:
        if mode=='rotation_probe':
            # Original serializer appends keys only in oracle mode.
            # Use the same exact input format with an explicit probe header.
            header=f"{mode} {len(case['cipher'])} {case['cut']} {case.get('period',13)} 8 6 {case['decoder_seed']} {int(case['selective_F'])} {phase}"
            parts=[header]+[' '.join(map(str,case[n])) for n in ['cipher','starts','ends']]
            parts+=[' '.join(format(float(x),'.17g') for x in np.asarray(model['log']).ravel()),
                    ' '.join(format(float(x),'.17g') for x in model['unigram_log']),
                    ' '.join(map(str,key))]
            answer=subprocess.run([str(BINARY)],input='\n'.join(parts)+'\n',text=True,
                                  capture_output=True,check=True,timeout=120)
            return json.loads(answer.stdout)
        return old.run_engine(case,model,mode,key,phase)
    finally:
        old.BINARY=previous


def load_models():
    raw=json.loads((ROOT/'recovery_benchmark_models.json').read_text())['models']
    for m in raw.values():
        m['log']=np.asarray(m['log']);m['unigram_log']=np.asarray(m['unigram_log'])
    return raw


def prepare():
    refs,words,_=old.sources_and_models()
    previous=json.loads((ROOT/'recovery_benchmark_cases.json').read_text())['cases']
    cases=[];overlaps=[]
    for index,name in enumerate(old.TARGETS):
        plain=refs[name];n=len(plain);starts=[0]*n;ends=[0]*n
        for word in words[name]:
            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))
        for trial in range(4):
            seed=330189+100*index+trial;rng=random.Random(seed)
            key=[rng.randrange(29) for _ in range(13)]
            prior=[c['id'] for c in previous if c['planted_key']==key and c['source']==name]
            if prior:overlaps.append({'source':name,'trial':trial,'seed':seed,'previous_cases':prior})
            for kind in (['no_exceptions','selective_F'] if trial==0 else ['selective_F']):
                cipher=[];skips=[];phase=ordinal=0
                for i,p in enumerate(plain):
                    skip=kind=='selective_F' and p==0 and ordinal%2==trial%2
                    if p==0:ordinal+=1
                    if skip:cipher.append(0);skips.append(i)
                    else:cipher.append((p+key[phase])%29);phase=(phase+1)%13
                cases.append({'id':f'{name}_{kind}_{trial}','source':name,'trial':trial,
                              'kind':kind,'construction_seed':seed,
                              'decoder_seed':890000+100*index+10*trial+int(kind=='selective_F'),
                              'cipher':cipher,'starts':starts,'ends':ends,'cut':cut,
                              'selective_F':kind=='selective_F','planted_key':key,
                              'planted_F_offsets':skips,'prior_key_cases':prior,
                              'gold_plaintext_sha256':old.digest(plain)})
    assert len(cases)==20 and len(overlaps)==4
    assert not any(c['cipher']==p['cipher'] for c in cases for p in previous)
    old.dump('rotation_recovery_cases.json',{'session':89,'cases':cases,
             'all_ciphertexts_distinct_from_session88':True,'seed_overlap':overlaps})
    old.dump(SPEC.name,{'session':89,'saved_before_fresh_recovery':True,
        'inherited_plan_sha256':old.sha(PLAN),'driver_sha256':old.sha(Path(__file__)),
        'engine_sha256':old.sha(ENGINE),'cases_sha256':old.sha(ROOT/'rotation_recovery_cases.json'),
        'models_sha256':old.sha(ROOT/'recovery_benchmark_models.json'),
        'original_driver_sha256':old.sha(ROOT/'recovery_benchmark.py'),
        'original_engine_sha256':old.sha(ROOT/'recovery_benchmark_engine.cpp'),
        'decoder_seed_rule':'890000 + 100*source_index + 10*trial + int(selective_F)',
        'paired_methods':METHODS,'restarts':8,'maximum_sweeps_per_restart':6,
        'rotation_rule':'After each coordinate sweep, score all thirteen cyclic left rotations from the same current array. Strict improvement greater than 1e-10; identity wins ties. Continue within six sweeps.',
        'randomness':'Same decoder seed per paired case. Shared RNG implementation is unchanged; if rotation changes early stopping, subsequent restart draws or shuffle orders may diverge. No claim of identical per-restart starts.',
        'gate':'For each method separately, all 20 positive cases must recover the exact 13-slot planted array and at least .95 prefix and continuation rune accuracy. No automatic unsolved search.',
        'seed_correction':'Four trial-zero arrays equal Session 88 trial-one arrays, with the opposite F mask. Twelve arrays are new. All 20 ciphertexts are new. Keep declared seeds; do not relabel all 16 arrays as fresh.',
        'seed_overlap':overlaps,
        'time_limit_seconds_per_process':120,
        'no_unsolved_section_search':True})
    print('PREPARED 20 new ciphertexts; 12 new key arrays, 4 prior arrays with new masks',flush=True)


def verify_spec():
    spec=json.loads(SPEC.read_text())
    for field,path in [('inherited_plan_sha256',PLAN),('driver_sha256',Path(__file__)),
                       ('engine_sha256',ENGINE),('cases_sha256',ROOT/'rotation_recovery_cases.json'),
                       ('models_sha256',ROOT/'recovery_benchmark_models.json'),
                       ('original_driver_sha256',ROOT/'recovery_benchmark.py'),
                       ('original_engine_sha256',ROOT/'recovery_benchmark_engine.cpp')]:
        assert spec[field]==old.sha(path),(field,path)


def fixtures():
    verify_spec();compile_engine();old.compile_engine()
    rng=np.random.default_rng(330189);checks=[]
    for trial in range(32):
        period=1+trial%4;cipher=rng.integers(0,29,8).tolist()
        if trial%4==0:cipher=[1 if c==0 else c for c in cipher]
        elif trial%4==1:cipher[2:5]=[0,0,0]
        elif trial%4==2:cipher[0]=cipher[-1]=0
        else:cipher=[0]*8
        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 selective in (False,True):
            case={'cipher':cipher,'starts':[1,0,1,1,0,0,1,0],
                  'ends':[0,1,1,0,0,1,0,1],'cut':3,'period':period,
                  'selective_F':selective,'decoder_seed':890000+trial}
            a=old.run_engine(case,model,'oracle',key,phase)
            b=run(case,model,'oracle',key,phase)
            for field in ['key','prefix','suffix','winning_restart','evaluations']:assert a[field]==b[field]
            probe=run(case,model,'rotation_probe',key,phase)
            scores=[]
            for shift in range(period):
                rotated=key[shift:]+key[:shift]
                score,_=old.brute(cipher[:3],case['starts'][:3],case['ends'][:3],rotated,model,selective,phase)
                scores.append(score)
            assert np.allclose(scores,probe['rotation_scores'],atol=1e-8,rtol=0)
            choice=0;top=scores[0]
            for shift,score in enumerate(scores):
                if score>top+1e-10:top=score;choice=shift
            assert probe['key']==key[choice:]+key[:choice]
            assert abs(probe['prefix']['score']-max(scores))<1e-8
            decoded=old.scalar(cipher[:3],case['starts'][:3],case['ends'][:3],probe['key'],
                               set(probe['prefix']['skips']),model,selective,phase)
            assert decoded[0]==probe['prefix']['plaintext'] and decoded[1]==probe['prefix']['end_phase']
            post=old.scalar(cipher[3:],case['starts'][3:],case['ends'][3:],probe['key'],
                            set(probe['suffix']['skips']),model,selective,probe['prefix']['end_phase'])
            optimum,_=old.brute(cipher[3:],case['starts'][3:],case['ends'][3:],probe['key'],model,selective,probe['prefix']['end_phase'])
            assert post[0]==probe['suffix']['plaintext'] and abs(post[2]-optimum)<1e-8
            if phase==0:
                original=old.run_engine(case,model)
                copied=run(case,model)
                for field in ['key','prefix','suffix','winning_restart','evaluations']:assert original[field]==copied[field]
            checks.append({'trial':trial,'period':period,'selective_F':selective,
                           'fixed_key_parity':True,'every_rotation_matches_exhaustive_F_masks':True,
                           'rotation_choice_optimal':True,'scalar_inverse_and_frozen_continuation':True,
                           'ordinary_fit_parity':phase==0})
    old.dump('rotation_recovery_fixtures.json',{'session':89,'execution_sha256':old.sha(SPEC),
              'fixtures':32,'policy_checks':checks,'passed':True,
              'ordinary_fit_parity_checks':sum(c['ordinary_fit_parity'] for c in checks)})
    print('FIXTURES PASS',len(checks),flush=True)


def gate(result):
    return result.get('key_exact',False) and result.get('prefix_rune_accuracy',0)>=.95 and result.get('continuation_rune_accuracy',0)>=.95


def benchmark():
    verify_spec();fixture=json.loads((ROOT/'rotation_recovery_fixtures.json').read_text())
    assert fixture['passed'] and fixture['execution_sha256']==old.sha(SPEC)
    compile_engine();refs,_,_=old.sources_and_models();models=load_models()
    cases=json.loads((ROOT/'rotation_recovery_cases.json').read_text())['cases'];rows=[]
    for case in cases:
        model=models[case['source']];gold=refs[case['source']]
        row={k:case[k] for k in ['id','source','trial','kind','prior_key_cases']}
        row.update(runes=len(gold),prefix_runes=case['cut'],continuation_runes=len(gold)-case['cut'])
        for method,mode in METHODS.items():
            row[method]=old.grade(case,run(case,model,mode),model,gold)
            row[method]['gate_case_passed']=gate(row[method])
        if case['selective_F']:
            row['supplied_key_path_diagnostic']=old.grade(case,run(case,model,'oracle',case['planted_key']),model,gold)
        rows.append(row)
        old.dump('rotation_recovery_results.json',{'session':89,'complete':False,'rows':rows})
        print(case['id'],{m:{k:row[m].get(k) for k in ['key_exact','prefix_rune_accuracy','continuation_rune_accuracy']} for m in METHODS},flush=True)
    summary={}
    for method in METHODS:
        summary[method]={'gate_passed':all(gate(r[method]) for r in rows),
                         'selective_F_full_exact':sum(r[method].get('full_output_exact',False) and r[method].get('key_exact',False) for r in rows if r['kind']=='selective_F'),
                         'no_exception_full_exact':sum(r[method].get('full_output_exact',False) and r[method].get('key_exact',False) for r in rows if r['kind']=='no_exceptions'),
                         'unresolved':sum(r[method]['status']!='completed' for r in rows)}
    old.dump('rotation_recovery_results.json',{'session':89,'complete':True,'summary':summary,'rows':rows,
              'execution_sha256':old.sha(SPEC),'fixtures_sha256':old.sha(ROOT/'rotation_recovery_fixtures.json'),
              'source_hashes':{name:old.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})
    print('SUMMARY',json.dumps(summary),flush=True)


def regressions():
    verify_spec();compile_engine();models=load_models();refs,_,_=old.sources_and_models()
    cases=json.loads((ROOT/'recovery_benchmark_cases.json').read_text())['cases']
    old_results=json.loads((ROOT/'recovery_benchmark_results.json').read_text())['rows']
    misses={r['id']:r['unknown_key'] for r in old_results if r['kind']=='selective_F' and not r['unknown_key']['key_exact']}
    rows=[]
    for case in cases:
        if case['id'] not in misses:continue
        result=old.grade(case,run(case,models[case['source']],'fit_rotations'),models[case['source']],refs[case['source']])
        rows.append({'id':case['id'],'original_result':misses[case['id']],'rotation_result':result})
    old.dump('rotation_recovery_regressions.json',{'session':89,'execution_sha256':old.sha(SPEC),
             'not_fresh_evidence':True,'session88_gate_still_failed':True,'rows':rows})
    print('REGRESSIONS',[(r['id'],r['rotation_result'].get('key_exact'),r['rotation_result'].get('full_output_exact')) for r in rows],flush=True)


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