"""Check the main audit by reconstructing four shifts directly. Uses published LP sources, not the signature runner.
python -B signatures_224_verify.py signatures_223_224_results.json.gz [evidence directory]"""
import sys,json,gzip
from pathlib import Path
from collections import Counter,defaultdict
D=Path(sys.argv[2]).resolve() if len(sys.argv)>2 else Path(__file__).resolve().parent;sys.path.insert(0,str(D))
from fixed_stream_133_135 import solved
from line_mechanism_108 import geometry
d=json.load(gzip.open(sys.argv[1]));P,_=solved();words=defaultdict(set)
for y,l in P.values():
    lst=[];a=0
    for n in l:
        u=tuple(map(int,y[a:a+n]));a+=n;lst.append(u)
        if len(u)>=8:words[(len(u),)].add(u)
    for a,b in zip(lst,lst[1:]):
        if len(a+b)>=10:words[len(a),len(b)].add(a+b)
_,ws=geometry();w8=[w for w in ws if w['section']==8];omit=set(d['excluded']);counts=[];hits=[]
for j,w in enumerate(w8):
    for seq in ([w],w8[j:j+2] if j+1<len(w8) else []):
        if not seq or any(w['rune_offset'] in omit for w in seq):continue
        shape=tuple(len(w['values']) for w in seq);length=sum(shape)
        if length<8 or (len(seq)==2 and length<10):continue
        at=seq[0]['rune_offset'];x=tuple(u for w in seq for u in w['values']);n1=n2=nf=0
        for y in words[shape]:
            shifts=tuple((c-a)%29 for c,a in zip(x,y))
            # Next rune must reuse the same shift as its earlier slot.
            n1+=shifts[4]==shifts[0];n2+=shifts[4:6]==shifts[:2]
            ok=all(s==shifts[i%4] for i,s in enumerate(shifts));nf+=ok
            if ok:hits.append((at,tuple(y)))
        counts.append([at,list(shape),len(words[shape]),n1,n2,nf])
assert counts==d['site_counts'] and {(a,w) for a,w in hits}=={(h['off'],tuple(h['w'])) for h in d['hits']}
print('Direct four-shift checks verified',sum(row[2] for row in counts),'site/form comparisons on',len(counts),'eligible sites.')
