"""Replay the May 19 prime-continuation proposal. Stdlib; run beside the notebook inputs.
Optional argument: raw early #cicadasolvers log, or GitHub's base64 blob JSON."""
import base64, hashlib, itertools, json, math, re, sys
from pathlib import Path
D = Path(__file__).resolve().parent
R = 'ᚠᚢᚦᚩᚱᚳᚷᚹᚻᚾᛁᛄᛇᛈᛉᛋᛏᛒᛖᛗᛚᛝᛟᛞᚪᚫᚣᛡᛠ'
LABEL = 'F U TH O R K G W H N I J EO P X S T B E M L ING OE D A AE Y IO EA'.split()
def archive(path):
    b=Path(path).read_bytes()
    if b.lstrip().startswith(b'{'):
        q=json.loads(b); assert q['encoding']=='base64'
        b=base64.b64decode(q['content']); assert len(b)==q['size']
    obj=hashlib.sha1(b'blob '+str(len(b)).encode()+b'\0'+b).hexdigest()
    assert obj=='bdd277c14f94c34b5ae714cd00c238065beeed4e' and len(b)==18487233
    ln=b.decode('utf-8',errors='replace').split('\n')
    may=[s for s in ln if s.startswith('2014 May ')]
    line=lambda n:ln[n-1].rstrip('\r')
    text=lambda n:line(n).split('> ',1)[1]
    ids=[n for n in range(176631,176645) if '<nikkler>' in line(n) and line(n).endswith('$')]
    runs=[len(m[0]) for n in ids for m in re.finditer(r'x{2,}',text(n))]
    target=''.join(text(165462).split())
    ctrl=json.loads((D/'page56_release_118.json').read_text())
    assert target==re.search(r'[0-9a-f]{128}',ctrl['reading'])[0]
    assert runs==json.loads((D/'handoff_119_results.json').read_text())['multispace_runs']
    assert '0wmWfct8' in line(177022) and 'including 19' in text(180883)
    assert len(may)==29249 and len({s[:11] for s in may})==31
    for n,t in [(180887,'WITHIN'),(180959,'primes - 1'),(181036,'DEEP'),(181040,'PAGE'),
                (181056,'page 55'),(181073,'backword'),(182151,'prime')]: assert t in text(n)
    return dict(blob=obj,bytes=len(b),may_entries=len(may),may_dates=31,spacing=runs,target_matches=True)
def experiment():
    master=(D/'liber-primus__transcription--master.txt').read_bytes()
    assert hashlib.sha256(master).hexdigest()=='b0b2e13c3cd35512ee5955a2d9a56c22d7410e283d35dd9c90abbaa7b99279eb'
    s=master.decode(); pages=s[s.index('ᚱ-'):].split('%')
    v=lambda page:[R.index(c) for c in pages[page] if c in R]
    train=[[(28-x)%29 for x in v(0)]]+[[(2-x)%29 for x in v(i)] for i in range(4,8)]+[v(i) for i in (3,8,9,10,11,14)]
    # Existing notebook LP1-only pair model, smoothing 0.2. No LP2 training.
    counts=[[.2]*29 for _ in range(29)]
    for group in train:
        for a,b in zip(group,group[1:]): counts[a][b]+=1
    L=[[math.log(x/sum(row)) for x in row] for row in counts]
    def score(xs):return sum(L[a][b] for a,b in zip(xs,xs[1:]))/(len(xs)-1)
    primes=[n for n in range(2,1200) if all(n%d for d in range(2,math.isqrt(n)+1))]
    def dec(ct,key,skips,reverse):
        values=ct.copy();k=0
        for j in (reversed(range(len(ct))) if reverse else range(len(ct))):
            if j in skips: assert ct[j]==0
            else: values[j]=(ct[j]-key[k]+1)%29;k+=1
        return values,k
    ct=v(71)
    pc,consumed=dec(ct,primes,{56},False)
    reference=json.loads((D/'increment_calibration_sources.json').read_text())['groups']
    assert any(g['values']==pc for g in reference) and len(pc)==85 and consumed==84
    ctrlkey=primes[:84]
    cr=[score(dec(ct,ctrlkey[j:]+ctrlkey[:j],{56},False)[0]) for j in range(84)]
    ct=v(70); f=[i for i,x in enumerate(ct) if x==0];seg=primes[consumed:consumed+len(ct)]
    assert len(ct)==76 and len(f)==3 and seg[0]==439 and primes[consumed-1]==433
    def candidates(key):
        for bits in itertools.product((False,True),repeat=len(f)):
            skips=[i for i,b in zip(f,bits) if b]
            for process_back in (False,True):
                xs,_=dec(ct,key,skips,process_back)
                for read_back in (False,True):
                    ys=xs[::-1] if read_back else xs
                    yield score(ys),skips,process_back,read_back,ys
    stages=[]
    for j in range(len(seg)):
        group=list(candidates(seg[j:]+seg[:j]))
        stages.append(max(x[0] for x in group))
        if j==0:
            actual=[dict(mean_log_score=round(sc,6),skip_at=sk,apply_backwards=pr,read_backwards=rr,
                         rune_labels=' '.join(LABEL[x] for x in ys)) for sc,sk,pr,rr,ys in group]
    return dict(page56_exact_runes=len(pc),primes_used=consumed,last_prime=primes[consumed-1],
       control_rank=1+sum(s>=cr[0]-1e-12 for s in cr[1:]),control_phases=len(cr),
       next_prime=seg[0],page55_runes=len(ct),page55_F_positions_zero_based=f,
       variants_per_phase=len(actual),rotations_total=len(stages),historical_phase_rank=1+sum(s>=stages[0]-1e-12 for s in stages[1:]),
       phase_best_scores=[round(s,6) for s in stages],historical_variants=actual)
if __name__=='__main__':
    out=experiment()
    if len(sys.argv)>1:out['verified_log']=archive(sys.argv[1])
    print(json.dumps(out,indent=1))
