"""Count the (2,0,2) repeated stratum by a four-cycle of pair compatibility matrices."""
from itertools import combinations
from functools import lru_cache
from longueurs28 import transfer
import json
from math import comb
def accepts(times,N,k):
    # Visit times have prescribed shifts. An automaton enforces both boundary dwells.
    fixed=dict(times);states={(s,0,0) for s in (-1,0,1)}
    for slot in range(N):
        new=set()
        for s,age,c in states:
            for v in (s,) if age<2 or c==k else (-1,0,1):
                if slot in fixed and fixed[slot]!=v:continue
                new.add((v,min(2,age+1) if v==s else 1,c+int(s!=v)))
        states=new
    return any(age==2 for _,age,_ in states)
def count(n,k):
    pool=list(combinations(range(n),2));active=(0,2,3,5);edges=[]
    for a,b in zip(active,active[1:]+active[:1]):
        constraints=[]
        for d in range(6):
            shifts=dict(((d+j+5)%6,j) for j in (-1,0,1))
            if a in shifts and b in shifts:constraints.append((shifts[a],shifts[b]))
        assert constraints
        edges.append([[int(all(accepts([(6*t+a,x) for t in left]+[(6*t+b,y) for t in right],6*n,k) for x,y in constraints)) for right in pool] for left in pool])
    import numpy as np
    M=[np.array(edge,dtype=object) for edge in edges]
    return int(np.trace(M[0]@M[1]@M[2]@M[3]))
def alternating_count(n):
    import numpy as np
    pairs=list(combinations(range(n),2));m=[]
    for a,b in ((0,2),(2,3),(3,5),(5,0)):
        def allowed(X,Y):
            labels=[v for _,v in sorted([(6*t+a,0) for t in X]+[(6*t+b,1) for t in Y])]
            return labels not in ([0,1,0,1],[1,0,1,0])
        m.append(np.array([[int(allowed(X,Y)) for Y in pairs] for X in pairs],dtype=object))
    return int(np.trace(m[0]@m[1]@m[2]@m[3]))
def study():
    out=[];coef={}
    for n in range(2,11):
        two=alternating_count(n);three=comb(n,2)**4;gain=three-two
        if n<=8:coef[n]=gain-sum(v*comb(n,h) for h,v in coef.items())
        assert gain==sum(v*comb(n,h) for h,v in coef.items())
        if n<=6:
            assert [two,three]==[count(n,k) for k in (2,3)]==[transfer(n,(2,0,2)*2,k) for k in (2,3)]
        out.append(dict(turns=n,two=two,three=three,gain=gain,size=n*(n-1)//2))
    return dict(rows=out,coefficients=coef)
if __name__=='__main__':print(json.dumps(study()))
