"""S217–218. Replay from the notebook evidence directory:
python -B lag_217_section.py lag_217_218_results.json
For a split working tree add --evidence DIR --control calibration_results.json.gz.
"""
import argparse, gzip, hashlib, json, math, sys
from collections import Counter
from pathlib import Path
import numpy as np

Q, L, ANCHOR = 29, 4, 12203
WORDS = [(40,101),(42,112),(46,7),(51,89)]

def close(x,y):
    return np.allclose(x,y,rtol=0,atol=2e-14)

def tally(x):
    return Counter((int(x[i])-int(x[i-L]))%Q for i in range(L,len(x)))

def prob(c):
    return [(c[t]+1)/(sum(c.values())+Q) for t in range(Q)]

def model(p):
    return [math.fsum(c[t] for c in p)/len(p) for t in range(Q)]

def dot(h,q):
    return math.fsum(n*math.log2(Q*q[t]) for t,n in enumerate(h))/sum(h)

def pairs(x,q,lo,hi,excluded=frozenset(),mode='full'):
    a=np.asarray(x,dtype=np.int64)
    keep=[i for i in range(lo,hi-L)
          if mode=='full' or (mode=='end' and i not in excluded and i+L not in excluded)
          or (mode=='strict' and not any(j in excluded for j in range(i,i+L+1)))]
    counts=[0]*Q
    for i in keep: counts[(int(x[i+L])-int(x[i]))%Q]+=1
    # Independent direction/placement & non-stitching check with vector coordinates.
    loc=np.arange(lo,hi-L)
    forbidden=np.asarray([i in excluded for i in range(len(a))])
    ok=np.ones(len(loc),dtype=bool)
    if mode!='full':
        for k in ([0,L] if mode=='end' else range(L+1)):ok &= ~forbidden[loc+k]
    loc=loc[ok]
    d=(a[loc+L]-a[loc])%Q
    assert keep==loc.tolist() and counts==np.bincount(d,minlength=Q).tolist()
    v=dot(counts,q)
    assert close(v,np.log2(Q*np.asarray(q))[d].mean())
    return dict(n=len(keep),hist=counts,score=v),keep

def recover(x,active,edges):
    # edges point forward along four disjoint residue chains. Recover ciphertext from
    # one actual starting rune per surviving connected component + its ordered differences.
    active=set(active); edges=set(edges); seeds=sorted(i for i in active if i-L not in edges)
    reproduced={i:int(x[i]) for i in seeds}
    for i in sorted(edges):
        assert i in reproduced and i+L in active
        reproduced[i+L]=(reproduced[i]+int((int(x[i+L])-int(x[i]))%Q))%Q
    assert set(reproduced)==active and all(v==int(x[i]) for i,v in reproduced.items())
    assert len(seeds)==len(active)-len(edges)
    return dict(vertices=len(active),edges=len(edges),components=len(seeds),
                components_by_section_residue=[sum(i%4==r for i in seeds) for r in range(4)])

def families(x,start,oldstarts):
    x=np.asarray(x,dtype=np.int16);n=len(x)
    ids=np.arange(Q**L,dtype=np.int32)
    ks=np.stack([(ids//Q**j)%Q for j in range(L)],axis=1).astype(np.int16)
    base=ANCHOR-start;slot=(np.arange(n)+start-ANCHOR)%L
    known=(x[base:base+L]-ks)%Q
    raw=(x[L:]-x[:-L])%Q
    taken=np.zeros(len(ks),dtype=bool);family=[]
    for (page,_),a,want in zip(WORDS[:3],oldstarts[:3],[841,29,29],strict=True):
        comparable=(x[a:a+L]-ks[:,slot[a:a+L]])%Q
        same=np.all(known==comparable,axis=1)
        assert not (taken&same).any() and int(same.sum())==want
        taken |= same
        for chunk in np.array_split(ks[same],max(1,(want+31)//32)):
            plain=(x[None,:]-chunk[:,slot])%Q
            assert np.array_equal((plain+chunk[:,slot])%Q,np.broadcast_to(x,plain.shape))
            assert np.all((plain[:,L:]-plain[:,:-L])%Q==raw)
        family.append(dict(page=page,keys=want,ordered_lag_4_positions=len(raw),all_identical=True,round_trip=True))
    odd=np.array([0,0,0,0,1,1,1,1],dtype=np.int16)
    alt=(x+odd[(np.arange(n)+start-ANCHOR)%8])%Q
    alt_d=(alt[L:]-alt[:-L])%Q;changed=int((alt_d!=raw).sum())
    assert changed==len(raw)
    return dict(all_key_count=int(len(ks)),family_keys_verified=int(taken.sum()),families=family,
                ordered_edges=len(raw),changed_under_primitive_8=changed,primitive_8_key=odd.tolist())

def run(evd,controlfile):
    # Read and validate the external gate decision before any scoring of unsolved material.
    packed=controlfile.read_bytes();c=json.loads(gzip.decompress(packed));group=c['groups']
    counts={k:sum(sum(min(v[k])>0 for v in z['trials']) for z in group.values()) for k in ('3','5','7','rotation')}
    npos=sum(min(v['positive'])>0 for v in group.values())
    assert c['distinct_positive']==npos and counts==c['negative']
    passed=npos>=5 and all(i<=22 for i in counts.values())
    assert c['gate']==passed

    src=json.loads((evd/'increment_calibration_sources.json').read_text())['groups']
    solved={g['name']:list(map(int,g['values'])) for g in src if g['name'] in group}
    assert len(solved)==len(group)==7
    p={k:prob(tally(t)) for k,t in solved.items()};allq=model(list(p.values()))
    assert close(allq,c['full_q'])
    ctl={};loo={}
    for k,Z in solved.items():
        six=model([t for h,t in p.items() if k!=h]);loo[k]=six
        h=len(Z)//2;v=[pairs(Z,six,0,h)[0]['score'],pairs(Z,six,h,len(Z))[0]['score']]
        assert close(v,group[k]['positive']) and close(six,group[k]['q']) and group[k]['n']==len(Z)
        ctl[k]=v
    sc=sorted(s for v in ctl.values() for s in v);bounds=[sc[0],sc[-1]]
    assert close(bounds,c['range'])
    sys.path.insert(0,str(evd))
    from line_mechanism_108 import geometry
    g,w=geometry()
    inds=[i for i,row in enumerate(g) if row[1]==8];start,end=inds[0],inds[-1]+1
    assert inds==list(range(start,end))
    x=[g[i][3] for i in inds];n=len(x);mid=n//2
    old=[next(t for t in w if (t['page'],t['page_rune_offset'])==v) for v in WORDS]
    assert all(t['section']==8 and len(t['values'])==4 for t in old) and old[-1]['rune_offset']==ANCHOR
    offsets=[t['rune_offset']-start for t in old]
    exc={j for a in offsets for j in range(a,a+L)};assert len(exc)==16
    spans=[(0,mid),(mid,n)]
    panel={};graphs={};hist={};locs={}
    for how in ('full','strict','end'):
        ab=[pairs(x,allq,lo,hi,exc,how) for lo,hi in spans]
        section,full_edges=pairs(x,allq,0,n,exc,how)
        hs=[z[0] for z in ab];hist[how]=hs
        locs[how]=[z[1] for z in ab]
        v=[q['score'] for q in hs]
        l={k:[dot(z['hist'],loo[k]) for z in hs] for k in loo}
        for k in loo:assert close(l[k],[pairs(x,loo[k],lo,hi,exc,how)[0]['score'] for lo,hi in spans])
        panel[how]=dict(halves=hs,loo=l,both_positive_count=sum(min(s)>0 for s in l.values()),
            raw_both_positive=min(v)>0,inside_control_range=[bounds[0]<=z<=bounds[1] for z in v])
        active=set(range(n))-(set() if how=='full' else exc)
        graphs[how]=dict(whole=recover(x,active,full_edges),
            split=recover(x,active,ab[0][1]+ab[1][1]),masked_unreported_values=n-len(active))
    assert locs['strict']==locs['end']
    matched={}
    for name,Z in solved.items():
        m=len(Z);u=m//2;vs=[]
        for how in ('full','strict'):
            vs.append([pairs(x,loo[name],lo,hi,exc,how)[0] for lo,hi in [(0,u),(n-(m-u),n)]])
        matched[name]=dict(group_length=m,held_source_half_scores=ctl[name],half_runes=[u,m-u],
            full=[v['score'] for v in vs[0]],masked=[v['score'] for v in vs[1]],
            full_pairs=[v['n'] for v in vs[0]],masked_pairs=[v['n'] for v in vs[1]])
    return dict(plan='lag_217_plan.txt',control_file_sha256=hashlib.sha256(packed).hexdigest(),
        known_source_file_sha256=hashlib.sha256((evd/'increment_calibration_sources.json').read_bytes()).hexdigest(),
        section_rune_byte_sha256=hashlib.sha256(bytes(x)).hexdigest(),reference=ANCHOR,
        gate=passed,distinct_positive=npos,wrong_key_accepts=counts,range=bounds,
        start=start,end_exclusive=end,midpoint_global=start+mid,n=n,
        pages=[g[start][0],g[end-1][0]],mask_words=[dict(page=t['page'],page_offset=t['page_rune_offset'],global_start=t['rune_offset'],end_exclusive=t['rune_offset']+L) for t in old],
        panel=panel,graphs=graphs,matched=matched,symmetry=families(x,start,offsets))

if __name__=='__main__':
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('output',type=Path)
    parser.add_argument('--evidence',type=Path,default=Path(__file__).resolve().parent)
    parser.add_argument('--control',type=Path)
    a=parser.parse_args();e=a.evidence.resolve()
    z=run(e,a.control or e/'lag_215_216_results.json.gz')
    a.output.write_text(json.dumps(z,indent=2,sort_keys=True)+'\n')
