"""Session98: frozen early/late geometry controls, with complete anchor words unscored.
Stages prepare, checks, benchmark. No unsolved ciphertext is fitted.
"""
from pathlib import Path
import argparse, hashlib, itertools, json, math, random, subprocess, time
import numpy as np
import paired_recovery as prev
rotation=prev.rotation; old=prev.old; ROOT=prev.ROOT
PLAN=ROOT/'early_anchor_recovery_next_plan.json'
ENGINE=ROOT/'early_anchor_recovery_engine.cpp'
BINARY=ROOT.parents[1]/'.sites-runtime/early-anchor-recovery-engine'
INPUT=ROOT/'early_anchor_recovery_inputs.json'
SPEC=ROOT/'early_anchor_recovery_execution.json'
CHECKS=ROOT/'early_anchor_recovery_checks.json'
RESULTS=ROOT/'early_anchor_recovery_results.json'
SOURCES=prev.SOURCES
PUBLIC=prev.PUBLIC+['score_mask']
read=prev.read; dump=prev.dump; sha=prev.sha

def public_case(c):return {k:c[k] for k in PUBLIC}

def payload(c,m,mode='fit_rotations',key=None,phase=0):
    h=f"{mode} {len(c['cipher'])} {c['cut']} {c['period']} 8 6 {c['decoder_seed']} {int(c['selective_F'])} {phase}"
    lines=[h]+[' '.join(map(str,c[k])) for k in ['cipher','starts','ends','score_mask']]
    lines+=[' '.join(format(float(v),'.17g') for v in np.asarray(m['log']).ravel()),' '.join(format(float(v),'.17g') for v in m['unigram_log'])]
    if mode=='oracle':assert key is not None;lines.append(' '.join(map(str,key)))
    else:assert key is None
    return '\n'.join(lines)+'\n'

def payload_hash(c,m):return hashlib.sha256(payload(public_case(c),m).encode()).hexdigest()

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(c,m,mode='fit_rotations',key=None,phase=0):
    start=time.monotonic()
    try:r=subprocess.run([str(BINARY)],input=payload(c,m,mode,key,phase),capture_output=True,text=True,timeout=120,check=True)
    except subprocess.TimeoutExpired:return {'status':'unresolved_timeout','wall_limit_seconds':120}
    a=json.loads(r.stdout);a.update(status='completed',elapsed_seconds=round(time.monotonic()-start,3));return a

def scalar(c,s,e,mask,key,skips,model,selective,phase=0):
    a=b=29;score=0.;plain=[];encoded=[]
    for i,value in enumerate(c):
        if s[i]:a=b=29
        if i in skips:
            assert selective and value==0;p=0;inverse=0
        else:p=(value-key[phase])%29;inverse=(p+key[phase])%29;phase=(phase+1)%len(key)
        assert inverse==value
        if mask[i]:
            score+=float(model['log'][a,b,p])
            if selective and (i in skips or p==0):score+=math.log(.5)
            if e[i]:score+=float(model['log'][b,p,29])
        plain.append(p);encoded.append(inverse);a,b=b,p
    assert encoded==c
    return plain,phase,score

def brute(c,s,e,mask,key,model,selective,phase):
    fs=[i for i,v in enumerate(c) if v==0] if selective else []
    best=-float('inf')
    for bits in itertools.product([False,True],repeat=len(fs)):
        skips={i for i,b in zip(fs,bits) if b}
        best=max(best,scalar(c,s,e,mask,key,skips,model,selective,phase)[2])
    return best

def evaluate(c,a,m,gold):
    if a['status']!='completed':return {'raw':a,'grade':{'status':a['status']}}
    cut=c['cut'];key=a['key'];out=[]
    for label,lo,hi,phase in [('prefix',0,cut,0),('suffix',cut,len(c['cipher']),a['prefix']['end_phase'])]:
        p=a[label];x=scalar(c['cipher'][lo:hi],c['starts'][lo:hi],c['ends'][lo:hi],c['score_mask'][lo:hi],key,set(p['skips']),m,c['selective_F'],phase)
        assert x[0]==p['plaintext'] and x[1]==p['end_phase'] and abs(x[2]-p['score'])<1e-7
        out+=x[0]
    denom=lambda lo,hi:sum(c['score_mask'][i]*(1+c['ends'][i]) for i in range(lo,hi))
    g={'status':'completed','key':key,'prefix_mean_score':a['prefix']['score']/denom(0,cut),
       'continuation_mean_score':a['suffix']['score']/denom(cut,len(out)),
       'prefix_scored_events':denom(0,cut),'continuation_scored_events':denom(cut,len(out)),
       'anchor_output':out[c['anchor_start']:c['anchor_start']+6],
       'prefix_end_phase':a['prefix']['end_phase'],'decoded_output_sha256':old.digest(out),
       'independent_scalar_reencryption':True,'key_and_prefix_state_frozen_before_continuation':True}
    if gold is not None:
        acc=lambda x,y:sum(a==b for a,b in zip(x,y))/len(y)
        g.update(key_exact=key==c['planted_key'],prefix_rune_accuracy=acc(out[:cut],gold[:cut]),continuation_rune_accuracy=acc(out[cut:],gold[cut:]),
          full_rune_accuracy=acc(out,gold),full_output_exact=out==gold,skip_mask_exact=a['prefix']['skips']+[i+cut for i in a['suffix']['skips']]==c['planted_F_offsets'],
          anchor_exact=g['anchor_output']==gold[c['anchor_start']:c['anchor_start']+6],prefix_terminal_phase_exact=a['prefix']['end_phase']==c['gold_prefix_end_phase'])
        g['positive_case_passed']=bool(g['key_exact'] and g['prefix_rune_accuracy']>=.95 and g['continuation_rune_accuracy']>=.95 and g['anchor_exact'] and g['prefix_terminal_phase_exact'])
    return {'raw':a,'grade':g}

def verify_archives():
    for name,wanted in read(PLAN)['input_hashes'].items():assert sha(ROOT/name)==wanted,name
    prev.verify();assert read(prev.RESULTS)['complete'] and read(prev.RESULTS)['overall_gate']=='pass'

def fill(words,count):
    result=[];left=count;index=0
    assert {2,3}<=set(map(len,words))
    while left:
        word=words[index%len(words)];index+=1
        if len(word)<=left and left-len(word)!=1:result.append(word);left-=len(word)
        assert index<100000
    return result

def constructed(source,refs,words,anchor):
    source_words=[refs[source][w['rune_offset']:w['rune_offset']+len(w['values'])] for w in words[source]]
    blocks=[fill(source_words,28)+[anchor[:3],anchor[3:]]+fill(source_words,1490),fill(source_words,3310)+[anchor[:3],anchor[3:]]]
    streams=[]
    for ws in blocks:
        plain=list(itertools.chain.from_iterable(ws));s=[];e=[]
        for w in ws:s.extend([1]+[0]*(len(w)-1));e.extend([0]*(len(w)-1)+[1])
        cut=max(i+1 for i,v in enumerate(e) if v and i+1<=int(.6*len(plain)))
        streams.append((plain,s,e,cut))
    return streams

def prepare():
    assert not any(p.exists() for p in [INPUT,SPEC,CHECKS,RESULTS]);verify_archives()
    refs,words,_=old.sources_and_models();models=rotation.load_models()
    previous=[c['planted_key'] for name in ['recovery_benchmark_cases.json','rotation_recovery_cases.json'] for c in read(ROOT/name)['cases'] if c['planted_key'] is not None]
    previous += [c['planted_key'] for p in read(prev.INPUT)['positive_pairs'] for c in p['streams']]
    positives=[];nulls=[];keys_seen=[];selections=[]
    for source_index,source in enumerate(SOURCES):
        anchor=list(prev.anchors(refs[source],words[source])[2]);layouts=constructed(source,refs,words,anchor)
        assert [len(t[0]) for t in layouts]==[1524,3316]
        assert models[source]['excluded_group']==source and source not in models[source]['training_groups']
        selections.append({'source':source,'anchor_values':anchor,'lengths':[1524,3316],'anchor_starts':[28,3310],'cuts':[t[3] for t in layouts]})
        for kind_index,kind in enumerate(['no_skip','selective_F']):
            selective=kind_index==1;seed=331098+100*source_index+kind_index;rng=random.Random(seed)
            skips=[]
            for si,(plain,*_) in enumerate(layouts):
                skips.append({i for ordinal,i in enumerate(i for i,p in enumerate(plain) if p==0) if selective and ordinal%2==si})
            anchors=[28,3310];phases=[(a-sum(i<a for i in sk))%13 for a,sk in zip(anchors,skips)]
            required={(phases[0]+j)%13:(-anchor[j])%29 for j in range(6)}
            key0=[rng.choice([v for v in range(29) if v!=required[slot]]) if slot in required else rng.randrange(29) for slot in range(13)]
            key1=[None]*13
            for j in range(13):
                value=key0[(phases[0]+j)%13];key1[(phases[1]+j)%13]=value if j<6 else rng.choice([v for v in range(29) if v!=value])
            keys=[key0,key1];assert key0!=key1 and all(k not in previous for k in keys);keys_seen+=keys
            pid=f'{source}_{kind}';streams=[]
            for si,((plain,s,e,cut),key,sk,a) in enumerate(zip(layouts,keys,skips,anchors)):
                mask=[1]*len(plain);mask[a:a+6]=[0]*6;cipher=prev.encrypt(plain,key,sk)
                c={'id':f'{pid}_s{si}','source':source,'kind':kind,'trial':0,'stream':si,'construction_seed':seed,
                  'cipher':cipher,'starts':s,'ends':e,'cut':cut,'period':13,'selective_F':selective,'score_mask':mask,
                  'decoder_seed':980000+100*source_index+10*kind_index+si,'anchor_start':a,'anchor_length':6,
                  'planted_key':key,'planted_F_offsets':sorted(sk),'gold_plaintext':plain,'gold_plaintext_sha256':old.digest(plain),
                  'gold_prefix_end_phase':(cut-sum(i<cut for i in sk))%13}
                c['public_fit_payload_sha256']=payload_hash(c,models[source]);streams.append(c)
            assert streams[0]['cipher'][28:34]==streams[1]['cipher'][3310:] and 0 not in streams[0]['cipher'][28:34]
            pair={'id':pid,'source':source,'kind':kind,'trial':0,'streams':streams,'gold_anchor_values':anchor,'gold_anchor_phases':phases};positives.append(pair)
            if not selective:continue
            for rep in range(9):
                nullseed=332098+1000*source_index+rep;rng=random.Random(nullseed);changed=[]
                for c in streams:
                    cipher=c['cipher'].copy()
                    for lo,hi in [(0,c['cut']),(c['cut'],len(cipher))]:
                        positions=[i for i in range(lo,hi) if c['score_mask'][i]];values=[cipher[i] for i in positions];rng.shuffle(values)
                        for i,v in zip(positions,values):cipher[i]=v
                    clone={**c,'id':f'{pid}_null{rep}_s{c["stream"]}','kind':'shuffled','cipher':cipher,'planted_key':None,'planted_F_offsets':None,'gold_plaintext':None,'gold_plaintext_sha256':None,'gold_prefix_end_phase':None,'null_seed':nullseed}
                    clone['public_fit_payload_sha256']=payload_hash(clone,models[source]);changed.append(clone)
                nulls.append({'id':f'{pid}_null{rep}','positive_pair_id':pid,'source':source,'kind':'shuffled','trial':0,'replicate':rep,'null_seed':nullseed,'streams':changed})
    assert len(positives)==6 and len(nulls)==27 and len({tuple(k) for k in keys_seen})==12
    dump(INPUT,{'session':98,'selections':selections,'positive_pairs':positives,'null_pairs':nulls,'artificial_cycled_vocabulary_not_independent_prose':True})
    dump(SPEC,{'session':98,'driver_sha256':sha(Path(__file__)),'plan_sha256':sha(PLAN),'input_sha256':sha(INPUT),'engine_sha256':sha(ENGINE),'models_sha256':sha(ROOT/'recovery_benchmark_models.json'),
       'unknown_key_fits':66,'supplied_key_diagnostics':12,'restarts':8,'sweeps':6,'process_timeout_seconds':120,'public_case_fields':PUBLIC,'equality_gold_or_planted_phase_in_fit_payload':False,'saved_before_checks_and_benchmark':True,'no_unsolved_text_fitting':True})
    print('PREPARED',json.dumps(selections),flush=True)

def verify():
    verify_archives();spec=read(SPEC)
    for field,path in [('driver_sha256',Path(__file__)),('plan_sha256',PLAN),('input_sha256',INPUT),('engine_sha256',ENGINE),('models_sha256',ROOT/'recovery_benchmark_models.json')]:assert spec[field]==sha(path),field

def checks():
    verify();assert not CHECKS.exists();data=read(INPUT);models=rotation.load_models();compile_engine();rotation.compile_engine();fixtures=[];probes=[]
    count=0;positives={p['id']:p for p in data['positive_pairs']}
    for pair in data['positive_pairs']+data['null_pairs']:
        for c in pair['streams']:
            n=len(c['cipher']);a=c['anchor_start'];cut=c['cut'];mask=c['score_mask']
            assert len(mask)==len(c['starts'])==len(c['ends'])==n and sum(mask)==n-6 and mask[a:a+6]==[0]*6
            assert c['starts'][a:a+6]==[1,0,0,1,0,0] and c['ends'][a:a+6]==[0,0,1,0,0,1]
            assert c['ends'][cut-1] and c['public_fit_payload_sha256']==payload_hash(c,models[c['source']]);count+=1
            if pair['kind']=='shuffled':
                basis=positives[pair['positive_pair_id']]['streams'][c['stream']]
                for field in ['score_mask','starts','ends','cut','decoder_seed']:assert c[field]==basis[field]
                for lo,hi in [(0,cut),(cut,n)]:assert sorted(c['cipher'][i] for i in range(lo,hi) if mask[i])==sorted(basis['cipher'][i] for i in range(lo,hi) if mask[i])
                assert c['cipher'][a:a+6]==basis['cipher'][a:a+6]
        c,d=pair['streams'];assert c['cipher'][c['anchor_start']:c['anchor_start']+6]==d['cipher'][d['anchor_start']:d['anchor_start']+6]
    rng=np.random.default_rng(331098)
    for trial in range(32):
        period=trial%4+1;pattern=trial//4;cipher=rng.integers(1,29,9).tolist()
        for i in ([0,1,8] if pattern%3==0 else [2,4,5] if pattern%3==1 else []):cipher[i]=0
        s=[1,0,0,1,0,1,0,0,0];e=[0,0,1,0,1,0,0,0,1];mask=[1]*9
        if pattern%2==0:mask[3:5]=[0,0]
        key=rng.integers(0,29,period).tolist();phase=trial%period
        model={'log':rng.normal(-3,1,(30,30,30)),'unigram_log':rng.normal(-4,1,29)}
        for selective in [False,True]:
            c={'cipher':cipher,'starts':s,'ends':e,'score_mask':mask,'cut':5,'period':period,'decoder_seed':989000+trial,'selective_F':selective}
            answer=run(c,model,'oracle',key,phase);assert answer['status']=='completed'
            for label,lo,hi,p0 in [('prefix',0,5,phase),('suffix',5,9,answer['prefix']['end_phase'])]:
                p=answer[label];args=[cipher[lo:hi],s[lo:hi],e[lo:hi],mask[lo:hi],key]
                replay=scalar(*args,set(p['skips']),model,selective,p0)
                assert replay[0]==p['plaintext'] and replay[1]==p['end_phase'] and abs(replay[2]-p['score'])<1e-8
                assert abs(brute(*args,model,selective,p0)-p['score'])<1e-8
            row={'trial':trial,'period':period,'policy':selective,'cipher':cipher,'starts':s,'ends':e,'score_mask':mask,'key':key,'phase':phase,'answer':answer,'exhaustive_scalar_pass':True}
            if all(mask):
                unchanged=rotation.run({k:v for k,v in c.items() if k!='score_mask'},model,'oracle',key,phase)
                assert {k:v for k,v in answer.items() if k not in ['elapsed_seconds']}=={k:v for k,v in unchanged.items() if k not in ['elapsed_seconds']}
                fitted=run(c,model);old_fit=rotation.run({k:v for k,v in c.items() if k!='score_mask'},model,'fit_rotations')
                assert {k:v for k,v in fitted.items() if k!='elapsed_seconds'}=={k:v for k,v in old_fit.items() if k!='elapsed_seconds'}
                row.update(all_ones_fixed_and_unknown_fit_parity=True,fit=fitted)
            fixtures.append(row)
    # Six paired probes, one prefix-anchor stream for each positive pair.
    for pair in data['positive_pairs']:
        c=public_case(pair['streams'][0]);changed={**c,'cipher':c['cipher'].copy()}
        for i,m in enumerate(c['score_mask']):
            if not m:
                assert c['cipher'][i]!=0
                changed['cipher'][i]=c['cipher'][i]%28+1
        model=models[pair['source']];a=run(c,model);b=run(changed,model)
        assert a['status']==b['status']=='completed' and a['key']==b['key'] and a['prefix']['score']==b['prefix']['score']
        probes.append({'id':pair['id'],'original_payload_sha256':payload_hash(c,model),'perturbed_payload_sha256':payload_hash(changed,model),'key':a['key'],'selection_score':a['prefix']['score'],'key_and_score_identical':True,'original':a,'perturbed':b})
    verify();dump(CHECKS,{'session':98,'execution_sha256':sha(SPEC),'passed':True,'payloads_verified':count,'fixtures':fixtures,'paired_perturbation_probes':probes,'benchmark_fits_run':0})
    print('CHECKS PASS:64 policy fixtures,32 all-one fit parity checks,six paired perturbation probes,66 payloads',flush=True)

def fit_pair(pair,models,oracle=False):
    streams=[]
    for c in pair['streams']:
        m=models[c['source']];assert payload_hash(c,m)==c['public_fit_payload_sha256']
        a=run(public_case(c),m,'oracle' if oracle else 'fit_rotations',c['planted_key'] if oracle else None)
        streams.append({'id':c['id'],**evaluate(c,a,m,c['gold_plaintext'])})
    complete=all(s['grade']['status']=='completed' for s in streams)
    row={k:pair[k] for k in ['id','source','kind','trial']};row.update(streams=streams,anchor_agreement=streams[0]['grade']['anchor_output']==streams[1]['grade']['anchor_output'] if complete else None,supplied_key_diagnostic=oracle)
    if pair['kind']=='shuffled':row.update(positive_pair_id=pair['positive_pair_id'],replicate=pair['replicate'])
    else:row['positive_pair_passed']=bool(complete and row['anchor_agreement'] and all(s['grade']['positive_case_passed'] for s in streams))
    return row

def benchmark():
    verify();assert read(CHECKS)['passed'] and read(CHECKS)['execution_sha256']==sha(SPEC);assert not RESULTS.exists();compile_engine()
    data=read(INPUT);models=rotation.load_models();positive=[];nulls=[];oracles=[]
    def checkpoint():dump(RESULTS,{'session':98,'complete':False,'positive_pairs':positive,'null_pairs':nulls,'supplied_key_pairs':oracles})
    for pair in data['positive_pairs']:
        row=fit_pair(pair,models);positive.append(row);checkpoint();print('POSITIVE',pair['id'],row['positive_pair_passed'],[s['grade'].get('key_exact') for s in row['streams']],flush=True)
    for pair in data['null_pairs']:
        row=fit_pair(pair,models);nulls.append(row);checkpoint();print('NULL',pair['id'],row['anchor_agreement'],flush=True)
    for pair in data['positive_pairs']:
        row=fit_pair(pair,models,True);oracles.append(row);checkpoint();print('ORACLE',pair['id'],[s['grade'].get('full_output_exact') for s in row['streams']],flush=True)
    positive_gate='unresolved' if any(s['grade']['status']!='completed' for r in positive for s in r['streams']) else 'pass' if all(r['positive_pair_passed'] for r in positive) else 'fail'
    comparisons=[]
    for row in positive:
        if row['kind']=='no_skip':continue
        matching=[r for r in nulls if r['positive_pair_id']==row['id']];assert len(matching)==9
        complete=all(s['grade']['status']=='completed' for r in [row]+matching for s in r['streams']);margins=[]
        if complete:
            for si in range(2):
                for metric in ['prefix_mean_score','continuation_mean_score']:
                    p=row['streams'][si]['grade'][metric];q=max(r['streams'][si]['grade'][metric] for r in matching)
                    margins.append({'stream':si,'metric':metric,'positive':p,'null_maximum':q,'strictly_exceeds_all_nulls':p>q})
        comparisons.append({'id':row['id'],'gate':'unresolved' if not complete else 'pass' if all(m['strictly_exceeds_all_nulls'] for m in margins) else 'fail','margins':margins})
    score_gate='unresolved' if any(c['gate']=='unresolved' for c in comparisons) else 'pass' if all(c['gate']=='pass' for c in comparisons) else 'fail'
    overall='unresolved' if 'unresolved' in [positive_gate,score_gate] else 'pass' if positive_gate==score_gate=='pass' else 'fail';verify()
    dump(RESULTS,{'session':98,'complete':True,'positive_pairs':positive,'null_pairs':nulls,'supplied_key_pairs':oracles,'positive_gate':positive_gate,'score_gate':score_gate,'overall_gate':overall,'score_comparisons':comparisons,'unknown_key_fits':66,'supplied_key_diagnostics':12,'execution_sha256':sha(SPEC),'checks_sha256':sha(CHECKS),'positive_stream_keys_exact':sum(s['grade'].get('key_exact',False) for r in positive for s in r['streams']),'positive_stream_messages_exact':sum(s['grade'].get('full_output_exact',False) for r in positive for s in r['streams']),'positive_pairs_anchor_agree':sum(r['anchor_agreement'] is True for r in positive),'null_pairs_anchor_agree':sum(r['anchor_agreement'] is True for r in nulls),'no_unsolved_text_fitting':True,'no_new_plaintext':True})
    print('COMPLETE',positive_gate,score_gate,overall,flush=True)

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