"""Rotate a six-residue footprint. Compare order alone with the two-slot dwell rule."""
from itertools import combinations,product
from functools import lru_cache
from strate29 import accepts
from longueurs28 import transfer
import json

@lru_cache(None)
def local(n,d,visits,k):
    shifts={(d+j+5)%6:j for j in (-1,0,1)}
    prescribed=sorted((t,shifts[t%6]) for t in visits)
    changes=sum(a[1]!=b[1] for a,b in zip(prescribed,prescribed[1:]))
    return changes<=k,accepts(prescribed,6*n,k)

def study():
    base=(2,0,2)*2;cache={};out=[]
    for rotation in range(6):
        sizes=base[rotation:]+base[:rotation]
        if sizes not in cache:
            table=[]
            for n,k in product((2,3,4),(2,3)):
                allowed=sum_order=0;first=None
                for groups in product(*(combinations(range(n),m) for m in sizes)):
                    times=tuple(sorted(6*t+j for j,g in enumerate(groups) for t in g))
                    flags=[local(n,d,tuple(t for t in times if (t-d-5)%6 in (0,1,5)),k) for d in range(6)]
                    order,physical=map(all,zip(*flags));assert not physical or order
                    sum_order+=order;allowed+=physical
                    if order and not physical and first is None:first=times
                assert allowed==transfer(n,sizes,k)
                table.append(dict(turns=n,switches=k,ordered=sum_order,physical=allowed,counterexample=first))
            cache[sizes]=table
        out.append(dict(rotation=rotation,sizes=sizes,rows=cache[sizes]))
    return out
if __name__=='__main__':print(json.dumps(study()))
