"""Run in the evidence folder: python -B layout_210_grid.py layout_210_grid.json"""
from pathlib import Path
from itertools import product,combinations
from collections import Counter
import json,sys,re,hashlib
import numpy as np
from line_mechanism_108 import geometry,D
from lp_core import lp,R
def run():
    g,ws=geometry(); st=next(i for i,z in enumerate(g) if z[1]==8)
    post=next(i for i,z in enumerate(g) if z[0]==51)
    prev=g[post-1]; assert prev[0]==49
    # Every master line containing an ASCII alphanumeric must be one entire grid row.
    rows={}
    for p in [49,50,51]:
        a=[]
        for line in lp[p].splitlines():
            if not re.search('[A-Za-z0-9]',line):continue
            m=re.fullmatch(r'\s*([A-Za-z0-9]{2}(?:-[A-Za-z0-9]{2})*)/\s*',line); assert m,(p,line)
            a.append(m.group(1).split('-'))
        assert {len(v) for v in a}=={8};rows[p]=a
    assert [len(r) for r in rows.values()]==[10,13,9]
    # Regroup all grid letters without hyphens from original pages as an independent count.
    total=sum(len(re.findall(r'[A-Za-z0-9]',lp[p])) for p in rows)
    cells=sum(len(row) for rr in rows.values() for row in rr)
    nrows=sum(map(len,rows.values()))
    assert total==2*cells==16*nrows==512
    srcpins={x['file']:x['sha256'] for x in json.loads((D/'jpeg_source_manifest.json').read_text())['files']}
    photos={f'{p+17}.jpg':srcpins[f'{p+17}.jpg'] for p in rows}
    for nm,h in photos.items():assert hashlib.sha256((D/nm).read_bytes()).hexdigest()==h
    a=next(w for w in ws if w['rune_offset']==12203)
    sites=[w for w in ws if w['section']==8 and w is not a and len(w['values'])==4];assert len(sites)==136
    assert not any(w['rune_offset']<post<w['rune_offset']+4 for w in sites)
    keys=np.array([(0,)+k for k in product(range(29),repeat=3)],dtype=int)
    kanchor=(np.array(a['values'])-keys)%29
    old=[9741,10256,11240]
    shifts={};phase_free=set(); lookup={}
    for jump in range(4):
        hit={}; checked=Counter()
        for w in sites:
            off=w['rune_offset'];j=(off-a['rune_offset']-(jump if off<post else 0))%4
            checked[j]+=1
            # All four-shift keys sum to the same value in either word, independent of phase.
            if sum(a['values'])%29!=sum(w['values'])%29:inds=[]
            else:
                phase_free.add(off)
                correct=np.all(kanchor==(np.array(w['values'])-keys[:,(np.arange(4)+j)%4])%29,axis=1)
                inds=np.nonzero(correct)[0].tolist()
                # Independent cycle-walk: each edge from i to i+j fixes its key difference.
                delta=(np.array(w['values'])-np.array(a['values']))%29;seen=set();comps=0;ok=True
                for t in range(4):
                    if t in seen:continue
                    q=t;v=0;comps+=1
                    while q not in seen:
                        seen.add(q);v+=int(delta[q]);q=(q+j)%4
                    if v%29:ok=False
                assert len(inds)==(29**(comps-1) if ok else 0)
            if inds:hit[off]=set(inds)
            lookup[off]=[w['page'],w['page_rune_offset']]
        pairs={f'{x},{y}':len(hit[x]&hit[y]) for x,y in combinations(hit,2)}
        oldpairs={f'{x},{y}':len(hit.get(x,set())&hit.get(y,set())) for x,y in combinations(old,2)}
        shifts[jump]=dict(phase_counts=dict(checked),hits=[dict(rune_offset=o,page=lookup[o][0],page_rune_offset=lookup[o][1],normalized_keys=keys[sorted(v)].tolist()) for o,v in hit.items()],intersections_normalized=pairs,old_intersections_normalized=oldpairs)
    assert [len(h['normalized_keys'])*29 for h in shifts[0]['hits']]==[841,29,29]
    return dict(schema='A phase jump is extra ticks on passing the table. Anchor slot normalized to zero; shared additive shifts omitted.',section_start=st,first_rune_after_table=post,uninterrupted_slot_at_exit=(post-st)%4,rows_per_page={p:len(r) for p,r in rows.items()},cells=cells,alphanumeric_characters=total,source_photos=photos,models=dict(skip=0,per_row=nrows%4,per_cell=cells%4,per_character=total%4,restart_at_section_initial_slot=(st-post)%4),tested_sites=len(sites),four_sum_eligible=[dict(offset=o,page=lookup[o][0],page_offset=lookup[o][1]) for o in sorted(phase_free)],phase_results=shifts)
if __name__=='__main__':
    x=run();Path(sys.argv[1]).write_text(json.dumps(x,indent=2)+'\n')
    print(x['models'],x['sections'] if 'sections' in x else x['four_sum_eligible'])
    for j,r in x['phase_results'].items():print(j,[(z['page'],z['page_rune_offset'],len(z['normalized_keys'])) for z in r['hits']],r['intersections_normalized'])
