"""Independent residue test for all exploratory sites and separable check of single-rune ceiling."""
from pathlib import Path
import json,gzip,math,collections,itertools
from line_mechanism_108 import geometry
from lp_core import LET
D=Path(__file__).resolve().parent
def main():
    gg,ws=geometry();words={w['rune_offset']:(w['section'],w['values']) for w in ws};data=json.loads(gzip.decompress((D/'second_204_invariant_results.json.gz').read_bytes()));nn=hit=0
    for row in data['sites']:
        a,n,s,_,_=row['anchor'];A=words[a][1];good=set()
        for off,(sec,B) in words.items():
            if off==a or len(B)!=n or sec!=s:continue
            delta=[(y-x)%29 for x,y in zip(A,B)]
            for p in range(3,n+1):
                d=(off-a)%p;num=math.gcd(p,d);nn+=1
                # Differences must repeat by slot, and total zero on every cycle under rotation by d.
                if all(z==delta[i%p] for i,z in enumerate(delta)) and all(sum(delta[j:p:num])%29==0 for j in range(num)):good.add((off,p));hit+=1
        assert good=={(w['offset'],w['period']) for w in row['hits']}
    assert (nn,hit)==(660,3)
    sg=json.loads((D/'relay_204_singletons_results.json').read_text());a=sg['anchor'][-1];counts=[[0]*29 for _ in range(4)]
    for off,(s,y) in words.items():
        if s!=8 or len(y)!=1:continue
        for ch in ['A','I','O']:counts[(off-a)%4][(y[0]-LET.index(ch))%29]+=1
    best=sum(max(v) for v in counts);num=math.prod(v.count(max(v)) for v in counts)
    assert (best,num)==(sg['baseline']['max_satisfied'],sg['baseline']['keys_at_max'])
    print('Independent residue test:',nn,'candidate-period pairs,',hit,'survivors; singleton maximum',best,'in',num,'keys.')
if __name__=='__main__':main()
