"""Session 90: execute the 396 shuffled-cipher controls fixed in Session 89.

No key, model or parameter selection from continuation scores. No new positive
recovery claims and no fitting of unmodified unsolved text.
Run prepare, then checks, then benchmark. Historical companions are read only.
"""
from collections import Counter
from pathlib import Path
import argparse
import json
import platform
import random
import statistics
import subprocess

import recovery_benchmark as base
import rotation_recovery as recovery

ROOT=base.ROOT
PLAN=ROOT/'rotation_null_next_plan.json'
CASES=ROOT/'rotation_null_cases.json'
SPEC=ROOT/'rotation_null_execution.json'
CHECKS=ROOT/'rotation_null_checks.json'
RESULTS=ROOT/'rotation_null_results.json'
INPUTS=['rotation_null_next_plan.json','rotation_recovery.py',
        'recovery_benchmark.py','rotation_recovery_engine.cpp',
        'rotation_recovery_execution.json','rotation_recovery_fixtures.json',
        'rotation_recovery_cases.json','rotation_recovery_results.json',
        'recovery_benchmark_models.json','lp_core.py','lexical_words.py',
        'increment_calibration_sources.json','liber-primus__transcription--master.txt']


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


def prepare():
    assert not RESULTS.exists(),'Preserve recorded fits; do not regenerate their inputs.'
    recovery.verify_spec()
    sources=read(ROOT/'rotation_recovery_cases.json')['cases']
    cases=[];seen={};duplicates=[];unchanged=[]
    for index,name in enumerate(base.TARGETS):
        basis=next(c for c in sources if c['source']==name and c['kind']=='selective_F' and c['trial']==0)
        cut=basis['cut']
        for replicate in range(99):
            seed=330190+1000*index+replicate;rng=random.Random(seed)
            left=basis['cipher'][:cut].copy();right=basis['cipher'][cut:].copy()
            rng.shuffle(left);rng.shuffle(right)
            cipher=left+right;identity=f'{name}_null_{replicate:02d}'
            signature=(name,base.digest(cipher));prior=seen.get(signature)
            if prior:duplicates.append({'id':identity,'same_ciphertext_as':prior})
            else:seen[signature]=identity
            if cipher==basis['cipher']:unchanged.append(identity)
            cases.append({'id':identity,'source':name,'replicate':replicate,
                          'basis_id':basis['id'],'construction_seed':seed,
                          'decoder_seed':900000+1000*index+replicate,
                          'cipher':cipher,'starts':basis['starts'],'ends':basis['ends'],
                          'cut':cut,'selective_F':True,
                          'cipher_sha256':base.digest(cipher),'duplicate_of':prior})
    base.dump(CASES.name,{'session':90,'cases':cases,'duplicates':duplicates,
                         'unchanged_from_basis':unchanged,'no_redraws':True})
    base.dump(SPEC.name,{'session':90,'saved_before_any_null_fitting':True,
              'plan_sha256':base.sha(PLAN),'driver_sha256':base.sha(Path(__file__)),
              'cases_sha256':base.sha(CASES),
              'input_hashes':{name:base.sha(ROOT/name) for name in INPUTS},
              'case_order':'Four source groups in retained TARGETS order, replicate 0..98.',
              'method':'fit_rotations; exactly the Session 89 implementation and limits',
              'normalization':'Each score divided by rune count plus complete-word-ending count in that segment; unchanged grade helper.',
              'ranks':'For each positive and segment, rank = 1 + number of completed null scores >= its score. Rank 1 means it exceeds every completed null. Report ties and unresolved counts; ranks are descriptive.',
              'joint_counts':'Number of completed nulls simultaneously >= a given positive in both prefix and continuation mean score. No continuation-based refitting.',
              'positive_reuse':'Read all 16 rotation-method selective-F results from Session 89. No positive re-fitting, fresh-language claim or new recovery gate.',
              'failure_handling':'120-second timeout per process is unresolved; never retry with extra budget. Independent replay disagreement halts the experiment for investigation.',
              'python':platform.python_version(),
              'compiler':subprocess.check_output(['g++','--version'],text=True).splitlines()[0],
              'no_unsolved_section_search':True,'no_new_plaintext':True})
    print('PREPARED',len(cases),'controls; duplicates',len(duplicates),'unchanged',len(unchanged),flush=True)


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


def checks():
    verify();snapshot=read(CASES);cases=snapshot['cases'];assert len(cases)==396
    positive_cases={c['id']:c for c in read(ROOT/'rotation_recovery_cases.json')['cases']}
    rows=[]
    for index,name in enumerate(base.TARGETS):
        group=[c for c in cases if c['source']==name]
        assert len(group)==99 and [c['replicate'] for c in group]==list(range(99))
        for case in group:
            basis=positive_cases[case['basis_id']];cut=case['cut'];rep=case['replicate']
            assert case['starts']==basis['starts'] and case['ends']==basis['ends']
            assert cut==basis['cut'] and case['ends'][cut-1]
            assert Counter(case['cipher'][:cut])==Counter(basis['cipher'][:cut])
            assert Counter(case['cipher'][cut:])==Counter(basis['cipher'][cut:])
            assert case['construction_seed']==330190+1000*index+rep
            assert case['decoder_seed']==900000+1000*index+rep
            rng=random.Random(case['construction_seed'])
            left=basis['cipher'][:cut].copy();right=basis['cipher'][cut:].copy()
            rng.shuffle(left);rng.shuffle(right)
            assert left+right==case['cipher']
            assert base.digest(case['cipher'])==case['cipher_sha256']
            assert not any(k in case for k in ['planted_key','planted_F_offsets','gold_plaintext_sha256'])
        rows.append({'source':name,'cases':99,'independent_inventory_and_layout_checks':True,
                     'declared_rng_reconstruction':True,'gold_fields_absent':True})
    fixtures=read(ROOT/'rotation_recovery_fixtures.json')
    assert fixtures['passed'] and fixtures['execution_sha256']==base.sha(ROOT/'rotation_recovery_execution.json')
    positives=read(ROOT/'rotation_recovery_results.json')
    assert positives['complete'] and positives['summary']['rotations']['gate_passed']
    # Check summary arithmetic with a deliberately mixed set, including a tie
    # and an unresolved record. No decoder fits are added to the fixed scope.
    sample=[{'fit':{'status':'completed','prefix_mean_score':-3,'continuation_mean_score':-5}},
            {'fit':{'status':'completed','prefix_mean_score':-2,'continuation_mean_score':-6}},
            {'fit':{'status':'unresolved_timeout'}}]
    s=describe(sample)
    assert s['completed']==2 and s['unresolved']==1 and s['prefix']['median']==-2.5
    assert compare(s,{'prefix_mean_score':-2,'continuation_mean_score':-5})['joint_null_count']==0
    assert compare(s,{'prefix_mean_score':-2,'continuation_mean_score':-5})['prefix_rank']==2
    assert compare(s,{'prefix_mean_score':-2,'continuation_mean_score':-5})['continuation_rank']==2
    base.dump(CHECKS.name,{'session':90,'execution_sha256':base.sha(SPEC),
               'passed':True,'construction_checks':rows,
               'summary_arithmetic_ties_and_unresolved':True,
               'retained_session89_decoder_fixtures_hash_verified':True,
               'retained_decoder_fixture_policy_checks':len(fixtures['policy_checks']),
               'no_extra_decoder_fits':True})
    print('CHECKS PASS: all 396 constructions, frozen dependencies, summary ties/timeouts',flush=True)


def describe(rows):
    good=[r['fit'] for r in rows if r['fit']['status']=='completed']
    stats={'completed':len(good),'unresolved':len(rows)-len(good),'scores':good}
    for segment,field in [('prefix','prefix_mean_score'),('continuation','continuation_mean_score')]:
        values=[r[field] for r in good]
        stats[segment]={'minimum':min(values),'median':statistics.median(values),'maximum':max(values)} if values else None
    return stats


def compare(stats,positive):
    good=stats['scores'];p=positive['prefix_mean_score'];s=positive['continuation_mean_score']
    return {'positive_prefix_mean_score':p,'positive_continuation_mean_score':s,
            'completed_nulls':stats['completed'],'unresolved_nulls':stats['unresolved'],
            'prefix_null_ge_count':sum(r['prefix_mean_score']>=p for r in good),
            'continuation_null_ge_count':sum(r['continuation_mean_score']>=s for r in good),
            'joint_null_count':sum(r['prefix_mean_score']>=p and r['continuation_mean_score']>=s for r in good),
            'prefix_rank':1+sum(r['prefix_mean_score']>=p for r in good),
            'continuation_rank':1+sum(r['continuation_mean_score']>=s for r in good),
            'prefix_tie_count':sum(r['prefix_mean_score']==p for r in good),
            'continuation_tie_count':sum(r['continuation_mean_score']==s for r in good),
            'prefix_margin_above_null_max':p-stats['prefix']['maximum'] if good else None,
            'continuation_margin_above_null_max':s-stats['continuation']['maximum'] if good else None}


def summaries(rows):
    positives=read(ROOT/'rotation_recovery_results.json')['rows'];out=[]
    for name in base.TARGETS:
        stats=describe([r for r in rows if r['source']==name])
        comparisons=[{'id':r['id'],'trial':r['trial'],**compare(stats,r['rotations'])}
                     for r in positives if r['source']==name and r['kind']=='selective_F']
        out.append({'source':name,**{k:v for k,v in stats.items() if k!='scores'},
                    'existing_positive_comparisons':comparisons})
    return out


def benchmark():
    verify();check=read(CHECKS)
    assert check['passed'] and check['execution_sha256']==base.sha(SPEC)
    assert not RESULTS.exists(),'Do not overwrite or rerun recorded controls.'
    recovery.compile_engine();models=recovery.load_models();rows=[]
    for case in read(CASES)['cases']:
        answer=recovery.run(case,models[case['source']],'fit_rotations')
        result=base.grade(case,answer,models[case['source']])
        rows.append({'id':case['id'],'source':case['source'],'replicate':case['replicate'],
                     'fit':result})
        base.dump(RESULTS.name,{'session':90,'complete':False,'execution_sha256':base.sha(SPEC),'rows':rows})
        if len(rows)%22==0 or len(rows)%99==0:
            print('COMPLETED',len(rows),'/396',case['source'],flush=True)
    verify()
    base.dump(RESULTS.name,{'session':90,'complete':True,'execution_sha256':base.sha(SPEC),
              'checks_sha256':base.sha(CHECKS),'rows':rows,'summary':summaries(rows),
              'no_unsolved_section_search':True,'no_new_plaintext':True,
              'no_new_positive_fits':True,'ranks_are_not_calibrated_p_values':True})
    print('COMPLETE',json.dumps(summaries(rows)),flush=True)


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