"""Exploratory replay: python3 -B relay_204_singletons.py results.json. Requires the notebook evidence directory, NumPy."""
import os,sys,json
from pathlib import Path
import numpy as np
D=Path(os.environ.get('CICADA_EVIDENCE_DIR',Path(__file__).resolve().parent))
sys.path.insert(0,str(D))
from line_mechanism_108 import geometry
from lp_core import LET
def run():
    geo,words=geometry()
    def word(p,o):
        return next(w for w in words if w['page']==p and w['page_rune_offset']==o)
    anchor=next(w for w in words if w['page']==51 and w['geo'][-1][0]==52 and [LET[v] for v in w['values']]==['P','L','F','P'])
    loc=anchor['rune_offset'];s=anchor['section'];assert s==8
    units=sorted((w for w in words if w['section']==s and len(w['values'])==1),key=lambda w:w['rune_offset'])
    count=29**4;ar=np.arange(count,dtype=np.int32);keys=np.stack([(ar//(29**j))%29 for j in range(4)],axis=1).astype(np.int16)
    prim=np.any(keys[:,:2]!=keys[:,2:],axis=1)
    score=np.zeros(count,dtype=np.uint8);allow=[LET.index(i) for i in ['A','I','O']]
    byslot=np.zeros((4,29),dtype=int)
    for i,w in enumerate(units):
        slot=(w['rune_offset']-loc)%4
        ok=np.isin((w['values'][0]-keys[:,slot])%29,allow);score+=ok
        byslot[slot]+=np.isin((w['values'][0]-np.arange(29))%29,allow)
        if i==0:first=ok
    assert np.array_equal(score,np.sum([byslot[i,keys[:,i]] for i in range(4)],axis=0))
    def summarize(mask):
        a=score[mask];n=len(units);mx=int(a.max())
        return dict(tested=len(a),max_satisfied=mx,keys_at_max=int((a==mx).sum()),all=int((a==n).sum()),earliest=int((first&mask).sum()),earliest_then_all_rest=int((first&mask&(score==n)).sum()),hist=np.bincount(a,minlength=n+1).tolist())
    groups=[];base=(np.array(anchor['values'])-keys)%29;from itertools import combinations
    masks=[]
    for (p,o),expected in zip([(40,101),(42,112),(46,7)],[841,29,29]):
        w=word(p,o);assert len(w['values'])==4 and w['section']==s;diff=w['rune_offset']-loc;mask=prim&np.all(base==(np.array(w['values'])-keys[:,(diff+np.arange(4))%4])%29,axis=1)
        assert mask.sum()==expected and all(not np.any(old&mask) for old in masks);masks.append(mask)
        groups.append(dict(page=p,offset=o,anchor_distance=diff,**summarize(mask)))
    out=dict(anchor=[anchor['page'],anchor['page_rune_offset'],loc],singletons=[dict(page=w['page'],page_offset=w['page_rune_offset'],offset=w['rune_offset'],rune=w['values'][0],slot=(w['rune_offset']-loc)%4) for w in units],baseline=summarize(np.ones(count,dtype=bool)),primitive=summarize(prim),families=groups)
    assert out['baseline']['max_satisfied']==int(byslot.max(1).sum())
    return out
if __name__=='__main__':Path(sys.argv[1]).write_text(json.dumps(run(),sort_keys=True,indent=2)+'\n')
