"""Paired page-break challenge. Run next to the retained Session 108 materials, NumPy required."""
from collections import defaultdict
from hashlib import sha256
from pathlib import Path
import json, re
import numpy as np
from lp_core import LET, pages, vals
from missing_inputs_108 import geometry, model, fit_key

D=Path(__file__).resolve().parent
def read(name):return json.loads((D/name).read_text())
def digest(value):return sha256(json.dumps(value,sort_keys=True,separators=(',',':')).encode()).hexdigest()


def letters(text):
    # One fixed experimental spelling; no claim about Cicada's choice of transliteration.
    rune={w:i for i,w in enumerate(LET)}
    order=sorted(rune,key=len,reverse=True)
    words=[]
    for w in re.findall('[A-Z]+',text.upper()):
        w=w.translate(str.maketrans({'C':'K','Q':'K','V':'U','Z':'S'}))
        acc=[]
        while w:
            k=next(k for k in order if w.startswith(k))
            acc.append(rune[k]);w=w[len(k):]
        words.append(acc)
    return words


def build_pair(row,seed):
    a,b=[letters(row['prefix']+' '+v) for v in row['ends']]
    suffix=letters(row['next'])
    flatten=lambda z:[x for w in z for x in w]
    A,B=flatten(a),flatten(b)
    assert [len(w) for w in a]==[len(w) for w in b] and A[:-1]==B[:-1] and A[-1]==0 and B[-1]!=0
    cut=len(A); per=row['period']; total=cut+len(flatten(suffix))
    rng=np.random.default_rng(seed); key=rng.integers(0,29,per).tolist()
    coins=rng.random(total)<.5
    pref_skip=[i for i in range(cut-1) if A[i]==0 and coins[i]]
    slot=(cut-1-len(pref_skip))%per
    key[slot]=(-B[-1])%29
    out=[]
    for ws,how in [(a,'skip'),(b,'advance')]:
        allwords=ws+suffix; plain=flatten(allwords)
        st=[int(j==0) for w in allwords for j in range(len(w))]
        en=[int(j==len(w)-1) for w in allwords for j in range(len(w))]
        mask={i for i,x in enumerate(plain) if x==0 and coins[i] and i!=cut-1}
        if how=='skip':mask.add(cut-1)
        c=[];phase=0
        for i,p in enumerate(plain):
            c.append(0 if i in mask else (p+key[phase])%29)
            if i not in mask:phase=(phase+1)%per
        out.append((dict(c=c,st=st,en=en,cut=cut,period=per),
                    dict(p=plain,k=key,skips=sorted(mask)),how))
    x,y=[z[0] for z in out]
    assert x['c'][:cut]==y['c'][:cut] and x['c'][cut-1]==0 and x['st']==y['st'] and x['en']==y['en']
    assert x['c'][cut:]!=y['c'][cut:]
    return out


# Nothing below in the fit or inference procedures receives the gold or passage label.
def seed_histories(c,L,u):
    shifts=(np.arange(29)[:,None]-np.arange(29)[None,:])%29
    emit=u[shifts]
    def rank(x):
        mat=x[0]
        a=mat.max(axis=1)
        return float(np.sum(a+np.log(np.exp(mat-a[:,None]).mean(axis=1)))+x[1])
    f=[i for i,v in enumerate(c) if v==0]
    beam=[(np.zeros((L,29)),0.,0,())]
    for j,stop in enumerate(f+[len(c)]):
        begin=0 if j==0 else f[j-1]+1
        if j:
            options=[]
            for mat,v,p,idx in beam:
                m=mat.copy();m[p]+=emit[0]
                options.append((m,v,(p+1)%L,idx))
                options.append((mat.copy(),v+u[0],p,idx+(begin-1,)))
            beam=options
        offsets=np.arange(stop-begin)
        # Precompute the normal (non-F) block's contributions for each incoming phase.
        delta=np.zeros((L,29))
        for i in offsets:delta[int(i)%L]+=emit[c[begin+int(i)]]
        tables=[np.roll(delta,p,axis=0) for p in range(L)]
        beam=[(m+tables[p],v,(p+len(offsets))%L,idx) for m,v,p,idx in beam]
        beam.sort(key=rank,reverse=True);beam=beam[:128]
    return list(dict.fromkeys([x[3] for x in beam[:12]]+[(),tuple(f)]))


# Each path carries: bigram score, decoded rune tuple, skip offsets, phase at the page cut.
def walk(c,st,en,key,t,left,right,states):
    L=len(key)
    for i in range(left,right):
        nxt={}
        for (ph,last),(v,past,fs,tag) in states.items():
            for skip in ((False,True) if c[i]==0 else (False,)):
                p=0 if skip else (c[i]-key[ph])%29
                val=v+t[29 if st[i] else last,p]+(t[p,29] if en[i] else 0.)
                state=(ph if skip else (ph+1)%L,29 if en[i] else p)
                if state not in nxt or val>nxt[state][0]:
                    nxt[state]=(val,past+(p,),fs+((i,) if skip else ()),tag)
        states=nxt
    return states


def best(states):return max(states,key=lambda s:states[s][0])
def initial():return {(0,29):(0.,(),(),None)}


def train_key(c,st,en,L,t,u):
    st=np.asarray(st,bool);en=np.asarray(en,bool); n=len(c)
    align=seed_histories(c,L,u); key_for={}; paths={}
    def fit(fs):
        if fs not in key_for:
            k,_,_=fit_key(c,L,set(fs),st,en,n,t,u)
            key_for[fs]=tuple(k)
        return key_for[fs]
    def path(k):
        if k not in paths:
            b=walk(c,st,en,k,t,0,n,initial()); paths[k]=b[best(b)]
        return paths[k]
    for fs in align:
        k=fit(fs)
        for z in range(3):
            nk=fit(path(k)[2])
            if nk==k:break
            k=nk
        path(k)
    winner=max(paths,key=lambda k:paths[k][0])
    return list(winner),{'seed_masks':len(align),'unique_keys_scored':len(paths),'prefix_score':float(paths[winner][0])}


def decode(x,key,t,delayed):
    c,st,en=x['c'],x['st'],x['en'];cut=x['cut']; end=cut+24
    states=walk(c,st,en,key,t,0,cut,initial())
    chosen={}
    if delayed:
        for state in states:
            ph=state[0]
            if ph not in chosen or states[state][0]>states[chosen[ph]][0]:chosen[ph]=state
    else:
        s=best(states);chosen[s[0]]=s
    outgoing={s:(*states[s][:3],s[0]) for s in chosen.values()}
    after=walk(c,st,en,key,t,cut,end,outgoing)
    b=best(after); tail=walk(c,st,en,key,t,end,len(c),{b:after[b]})
    _,p,fs,ph=tail[best(tail)]
    return {'p':list(p),'fs':list(fs),'phase':ph,'states_retained':len(chosen)}


def grade(x,y,k,pred):
    c,cut,L=x['c'],x['cut'],x['period']; p=pred['p']; fs=pred['fs']
    true_phase=(cut-sum(i<cut for i in y['skips']))%L
    pos=[i for i,(a,b) in enumerate(zip(p,y['p'])) if a!=b]
    # An inconsistent answer must not be counted as a plausible path.
    replay=[]; ph=0; masked=set(fs)
    for i,v in enumerate(p):
        if i in masked:
            assert v==0;replay.append(0)
        else:replay.append((v+k[ph])%29);ph=(ph+1)%L
    assert len(p)==len(c) and replay==c
    return {'key_correct':k==y['k'],'key_slots_correct':sum(a==b for a,b in zip(k,y['k'])),
            'seam_action_correct':((cut-1 in fs)==(cut-1 in y['skips'])),
            'true_phase':true_phase,'inferred_phase':pred['phase'],'phase_correct':pred['phase']==true_phase,
            'skips_correct':fs==y['skips'],'exact_text':not pos,'full_pass':k==y['k'] and fs==y['skips'] and not pos,
            'errors_prefix':sum(i<cut for i in pos),'errors_probe':sum(cut<=i<cut+24 for i in pos),
            'errors_tail':sum(i>=cut+24 for i in pos),'error_offsets':pos,'inferred_skips':fs,
            'states_retained':pred['states_retained'],'plaintext_hash':digest(p)}


def main():
    plans=read('phase_carry_109_plan.json'); prose=read('phase_carry_109_prose.json')
    rec={r['name']:r for r in read('mechanism_coverage_results.json')['known_method_groups']}
    gold={r['name']:r['values'] for r in read('increment_calibration_sources.json')['groups']}
    src={k:'%'.join(pages[i] for i in r['parsed_page_indices']) for k,r in rec.items()}
    t,u=model([(src[k],gold[k]) for k in rec]); ans={}
    def one(x,y,k,info,t):
        return dict(cut=x['cut'],n=len(x['c']),tail_n=len(x['c'])-x['cut']-24,period=x['period'],
                    prefix_sha=digest([x['c'][:x['cut']],x['st'][:x['cut']],x['en'][:x['cut']],x['period']]),
                    public_sha=digest(x),gold_sha=digest(y),key=k,gold_key=y['k'],gold_skips=y['skips'],fit=info,
                    **{m:grade(x,y,k,decode(x,k,t,q)) for m,q in [('greedy',False),('delayed',True)]},
                    oracle_key_delayed=grade(x,y,y['k'],decode(x,y['k'],t,True)))
    for row,seed in zip(prose,plans['constructor_seeds']):
        twins=build_pair(row,seed)
        x0=twins[0][0]; cut=x0['cut']
        # Both twins are deliberately identical on the exact inputs accepted by train_key.
        k,info=train_key(x0['c'][:cut],x0['st'][:cut],x0['en'][:cut],x0['period'],t,u)
        for x,y,name in twins:
            o=one(x,y,k,info,t);ans[row['tag']+'_'+name]=o
            print(row['tag'],name,o['greedy']['phase_correct'],o['delayed']['phase_correct'],o['delayed']['key_slots_correct'],o['delayed']['errors_tail'],o['delayed']['full_pass'],flush=True)
    group='welcome';st,en=geometry(src[group])
    x=dict(c=list(map(int,vals(src[group]))),cut=len(vals(pages[1])),st=st.astype(int).tolist(),en=en.astype(int).tolist(),period=8)
    y=dict(k=rec[group]['ordinal_key_values'],p=gold[group],skips=rec[group]['unenciphered_F_offsets'])
    tr,un=model([(src[k],gold[k]) for k in rec if k!=group]); cut=x['cut']
    k,info=train_key(x['c'][:cut],x['st'][:cut],x['en'][:cut],8,tr,un)
    reg=one(x,y,k,info,tr)
    total={method:{a:sum(r[method][a] for r in ans.values()) for a in ['key_correct','phase_correct','seam_action_correct','skips_correct','exact_text','full_pass','errors_prefix','errors_probe','errors_tail']} for method in ['greedy','delayed','oracle_key_delayed']}
    out=dict(plan_sha256=sha256((D/'phase_carry_109_plan.json').read_bytes()).hexdigest(),prose_sha256=sha256((D/'phase_carry_109_prose.json').read_bytes()).hexdigest(),
             cases=ans,totals=total,regression=reg,tail_total=sum(r['tail_n'] for r in ans.values()),fresh_gate=all(r['delayed']['full_pass'] for r in ans.values()))
    (D/'phase_carry_109_results.json').write_text(json.dumps(out,indent=2)+'\n')
    print(total,'tail',out['tail_total'],'regression',{m:[reg[m][i] for i in ['key_correct','phase_correct','errors_prefix','errors_probe','errors_tail']] for m in ['greedy','delayed','oracle_key_delayed']})

if __name__=='__main__':main()
