"""Secondary, retrospective diagnostic. Fixed before calculation after A-B-A failed.
Primary: pages 0-55, independent uniform cyclic rotation of word-join edge labels
inside each page x section. Sensitivity: each whole section to match Session 107.
Include zero offsets. Preserve all rune edges; never create last-to-first rune pairs.
Convolve all shift-count distributions; report exact tails and discrete 95% bounds.
"""
from collections import defaultdict
from pathlib import Path
import numpy as np,json
from line_mechanism_108 import D,geometry

def measure(blocks):
    dist=np.array([1.]);obs=edges=doubles=joins=0;mean=0; used=0
    for block in blocks.values():
        if len(block)<2:continue
        used+=1
        rune,word=np.array(block).T
        e=(rune[1:]==rune[:-1]); j=(word[1:]!=word[:-1]).astype('int16')
        n=len(j);ii=np.flatnonzero(e); ks=np.arange(n)
        vals=sum((j[(i-ks)%n] for i in ii),np.zeros(n,dtype=int))
        # All alignments counted once; verify zeroth rotation and exact first moment.
        assert vals[0]==np.sum(j[e]) and vals.sum()==len(ii)*j.sum()
        dist=np.convolve(dist,np.bincount(vals)/n)
        edges+=n;joins+=int(j.sum());doubles+=len(ii);obs+=int(vals[0]);mean+=len(ii)*j.mean()
    assert np.isclose(dist.sum(),1) and np.isclose(mean,np.arange(len(dist))@dist)
    pr=dist.cumsum()
    return dict(blocks=used,eligible_edges=edges,all_doubles=doubles,word_joins=joins,observed=obs,
                expected=float(mean),central_95=np.searchsorted(pr,[.025,.975]).tolist(),
                lower_inclusive=float(dist[:obs+1].sum()),upper_inclusive=float(dist[obs:].sum()),
                probabilities=dist.tolist())
def main():
    _,ws=geometry();page=defaultdict(list);sec=defaultdict(list)
    for wi,w in enumerate(ws):
        for pg,s,_,r in w['geo']:
            page[pg,s].append((r,wi));sec[s].append((r,wi))
    x=measure(page);y=measure(sec)
    assert (y['word_joins'],y['observed'],y['all_doubles'])==(2887,23,86)
    (D/'join_alignment_113.json').write_text(json.dumps(dict(page_section=x,section=y),indent=2)+'\n')
    for z in (x,y):print({k:v for k,v in z.items() if k!='probabilities'})
if __name__=='__main__':main()
