"""Independent second-word checks. Run in the evidence directory: python -B second_204_verify.py [evidence_dir]."""
from pathlib import Path
from collections import Counter
from itertools import accumulate
from hashlib import sha256
import gzip,json,re,sys
F=Path(sys.argv[1]) if len(sys.argv)>1 else Path(__file__).resolve().parent
R='ᚠᚢᚦᚩᚱᚳᚷᚹᚻᚾᛁᛄᛇᛈᛉᛋᛏᛒᛖᛗᛚᛝᛟᛞᚪᚫᚣᛡᛠ'
LE='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 read(name):
    return json.loads(gzip.decompress((F/name).read_bytes()))
def independent_words():
    """Strip page/line layout from a coordinate-tagged stream, then group rune runs by regular expression."""
    f=F/'liber-primus__transcription--master.txt';pin=json.loads((F/'three_tests_plan.json').read_text())['source_sha256']
    assert sha256(f.read_bytes()).hexdigest()==pin
    raw=f.read_text();body='%'.join(raw[raw.index('ᚱ-'):].split('%')[15:71])
    body=re.sub('(?<=['+R+"])['’](?=["+R+'])','',body)
    page=0;sec=0;off=0;local=0;codes=[];tag=[]
    for c in body:
        if c=='%':page+=1;local=0
        elif c=='/' or c.isspace():continue
        elif c in R:
            codes.append(c);tag.append((off,page,local,sec));off+=1;local+=1
        else:
            codes.append(':');tag.append(None);sec+=int(c=='$')
    result=[]
    for j,w in enumerate(re.finditer('['+R+']+',''.join(codes))):
        i,p,n,s=tag[w.start()];e,p1,n1,s1=tag[w.end()-1];assert i+len(w.group())-1==e and s==s1
        result.append({'id':j,'offset':i,'page':p,'local':n,'endpage':p1,'section':s,'c':tuple(map(R.index,w.group()))})
    assert len(result)==2896 and off==12956
    return result
def controls():
    data=read('relay_196_198_results.json.gz');tot=Counter()
    for row in data['rows']:
        c1,c2,w=row['c1'],row['c2'],row['w'];a,b,p=row['a'],row['b'],row['p'];key=row['k']
        def decrypt(c,start,key):return [(v-key[(start+j)%p])%29 for j,v in enumerate(c)]
        assert decrypt(c1,a,key)==decrypt(c2,b,key)==w
        slots=[None]*p
        for j,c in enumerate(c1):
            i=(a+j)%p;k=(c-w[j])%29;assert slots[i] in (None,k);slots[i]=k
        ix=[j for j in range(len(w)) if slots[(b+j)%p] is not None]
        assert ix==row['forced_ix'] and [(w[j]+slots[(b+j)%p])%29 for j in ix]==[c2[j] for j in ix]
        one=Counter();shameq=0;sh=row['sham']
        cx=[(v+key[(sh['b']+j)%p])%29 for j,v in enumerate(sh['w'])] if sh else []
        for i in range(p):
            for v in range(29):
                if v==key[i]:continue
                k=list(key);k[i]=v;u=decrypt(c1,a,k);t=decrypt(c2,b,k);both=u==t
                one.update(tested=1,equal=both,target_exact=t==w,anchor_and_target=u==t==w,wrong_common=both and t!=w,anchor_exact=u==w,anchor_exact_target_wrong=u==w!=t)
                if sh:shameq+=int(u==decrypt(cx,sh['b'],k))
        assert one==row['one']
        if sh:assert shameq==sh['one_equal']
        tot['one_slot_checks']+=one['tested'];tot['sham_one_slot_checks']+=(p*28 if sh else 0);tot['control_panels']+=1
    return tot
def negatives():
    d=read('seed_202_results.json.gz');n=read('join_185_194_results.json.gz')
    records={(x['si'],x['i'],x['arm']):x for x in n['rows']};tot=Counter()
    for z in d['records']:
        alpha=records[z['si'],z['i'],z['arm']];m=alpha['methods'][z['method']];k=m['k'];h=m['wins']['joined'];y=alpha['y'];cipher=alpha['x'];candidate=[(v-k[(i-h)%len(k)])%29 if i>=92 else None for i,v in enumerate(cipher)];bs=[(a,e) for a,e in alpha['bounds'] if 92<=a<e<=124]
        for race in ['first','cover']:
            picked=[]
            for a,e in bs:
                picked.append((a,e))
                if race=='first' or len({(i-h)%len(k) for i in (j for l,r in picked for j in range(l,r))})==len(k):break
            if race=='cover' and len({(i-h)%len(k) for a,e in picked for i in range(a,e)})!=len(k):picked=[]
            out=z[race]
            if not out:assert not picked;continue
            assert picked==list(map(tuple,out['bounds']))
            exact=all(candidate[a:e]==y[a:e] for a,e in picked);assert out['exact']==exact;tot['wrongbank_exact_checks']+=1
    return tot
def primary():
    words=independent_words();by={w['offset']:w for w in words};rows=json.loads((F/'second_195_manifest.json').read_text());d=read('second_203_204_results.json.gz');null=d['null']
    import numpy as np
    # Reuse only the pinned known plaintext/word lengths, never the new experiment's solver or token extraction.
    sys.path.insert(0,str(F));from fixed_stream_133_135 import solved
    known,_=solved();lex=set()
    for y,l in known.values():
        cuts=[0]+list(accumulate(l))
        lex.update(tuple(map(int,y[a:b])) for a,b in zip(cuts,cuts[1:]))
    gen=np.random.default_rng(2043301);tot=Counter();nullsites=np.zeros(4095,int);possible=0
    prior=read('join_194_cribs_results.json.gz');prior_keys={r['latin']:r['k'] for r in prior}
    for hand,o in zip(rows['sites'],d['sites'],strict=True):
        page=hand['page'];assert page==o['page']
        # Reading tags from individual runes gets the physical cut even when a word straddles two pages.
        length_left={27:3,17:4,48:8,51:3}[page];a=next(w for w in words if w['page']==page and w['endpage']==page+1) if page!=17 else max((w for w in words if w['page']==w['endpage']==17), key=lambda w:w['offset'])
        raw=(F/'liber-primus__transcription--master.txt').read_text();pp=raw[raw.index('ᚱ-'):].split('%')[15:71];physical=sum(c in R for s in pp[:page+1] for c in s)
        assert physical==hand['cut']==a['offset']+length_left
        def descr(w):return [w['offset'],len(w['c']),w['section'],w['page'],w['local']]
        assert hand['anchor']==descr(a) and list(a['c'])==o['cipher']
        n=len(a['c']); pool=[w for w in words if w['offset']>=physical+64 and len(w['c'])==n and w['section']==a['section']]
        assert hand['targets']==list(map(descr,pool))
        for ph in [1,2]:
            sel=next((w for w in pool if (w['offset']-a['offset'])%3==ph),None);key=str(ph);ss=o['selectors'][key]
            assert hand['chosen'][key]==(descr(sel) if sel else None)
            if sel is None:assert ss is None;continue
            assert ss['offset']==sel['offset'] and ss['actual']==list(sel['c'])
            if page!=51:assert not ss['forecast']
            else:
                assert set(r['word'] for r in ss['forecast'])=={'TEST','ELSE'}
                for prop in ss['forecast']:
                    w=[LE.index(c) for c in prop['word']];k=prior_keys[prop['word']]
                    assert [(c-k[(85+j)%3])%29 for j,c in enumerate(a['c'])]==w
                    pred=[(c+k[(85+ph+j)%3])%29 for j,c in enumerate(w)]
                    assert prop['pred']==pred and sum(t==u for t,u in zip(sel['c'],pred))==prop['agree']
        hypotheses={}
        for w in lex:
            if len(w)!=n:continue
            for p in [3,4,5,6,7,8,13]:
                if p>n:continue
                k=[(a['c'][i]-w[i])%29 for i in range(p)]
                if any((v-k[i%p])%29!=y for i,(v,y) in enumerate(zip(a['c'],w))):continue
                size=next(il for il in range(1,p+1) if all(k[i]==k[(i+il)%p] for i in range(p)))
                hypotheses.setdefault((w,tuple(k[:size])),[]).append(p)
        claimed={(tuple(e['w']),tuple(e['key'])):e for e in o['candidates']};assert claimed.keys()==hypotheses.keys()
        M=len(pool);adj=[set() for _ in pool];ncomp=Counter();nt=0
        for (w,k),ps in hypotheses.items():
            entry=claimed[w,k];p=len(k);assert p==entry['p'] and ps==entry['nominal']
            # Independent direction: decrypt actual words with the putative key, compare with the claimed anchor plaintext.
            # Check each stored full forward signature too.
            phases=[[(v+k[(j+rot)%p])%29 for j,v in enumerate(w)] for rot in range(p)]
            assert entry['by_phase']==phases
            hits=[]
            for i,slot in enumerate(pool):
                ph=(slot['offset']-a['offset'])%p
                for j,other in enumerate(pool):
                    match=all((c-k[(ph+t)%p])%29==v for t,(c,v) in enumerate(zip(other['c'],w)))
                    if match and ph:adj[i].add(j)
                    if i==j:
                        mode='shifted' if ph else 'aligned';ncomp[mode+'_tests']+=1
                        if match:hits.append([slot['offset'],ph]);ncomp[mode+'_hits']+=1
            assert hits==entry['hits'];nt+=len(ps)
        possible+=bool(any(adj));shuf=gen.permuted(np.tile(np.arange(M),(4095,1)),axis=1)
        counts=sum(any(int(v) in ok for v,ok in zip(line,adj)) for line in shuf)
        q=np.any(np.column_stack([np.isin(shuf[:,i],list(allowed)) for i,allowed in enumerate(adj)]),axis=1)
        assert counts==int(q.sum());nullsites+=q
        expect=dict(known_types=sum(len(w)==n for w in lex),nominal=nt,keys=len(claimed),positions=M,
                    aligned_tests=ncomp['aligned_tests'],shifted_tests=ncomp['shifted_tests'],aligned_hits=ncomp['aligned_hits'],shifted_hits=ncomp['shifted_hits'],
                    permutations_with_hit=counts,eligible_cells=sum(map(len,adj)))
        assert expect==o['tally'],(expect,o['tally'])
        tot['addresses']+=M;tot['hypotheses']+=len(claimed);tot['actual_key_address_pairs']+=sum(ncomp[s+'_tests'] for s in ['aligned','shifted'])
        tot['matrix_cells_checked']+=M*M;tot['candidate_matrix_evaluations']+=len(hypotheses)*M*M
    hist={str(k):int(v) for k,v in Counter(map(int,nullsites)).items()};obs=sum(bool(r['tally']['shifted_hits']) for r in d['sites']);ge=int(sum(nullsites>=obs))
    assert (null['observed'],null['ge'],null['M'],null['hist'],null['p'])==(obs,ge,4095,hist,(1+ge)/4096)
    tot['shuffled_word_assignments']=4095;tot['sites_where_any_within_stratum_permutation_could_hit']=possible
    return tot
if __name__=='__main__':
    counts=primary()
    for path,check in [('relay_196_198_results.json.gz',controls),('seed_202_results.json.gz',negatives)]:
        if (F/path).is_file():counts.update(check())
    print(json.dumps(counts,sort_keys=True))
