"""U two-step cells, step 1 (Grant pt216u): the F_p[t]/t^2 model.  Replace Z/p^2 by F_p[t]/(t^2) (p -> t in the
operator coefficients).  Then the glue G is an F_p-subspace of the expanded space with basis e_i (all i with delta>0)
and t*e_i (delta_i = 2), invariant under multiplication by t and the operators, with no coordinate vector inside and
every coordinate functional nonzero -- exactly count.py's count_glue problem (entries 0, +-1)."""
import json, sys, sympy as sp
from uniform import induced
from count import count_glue, P, BAD
A=[0,4,5,6]; B=[1,2,3,7]
def expanded(al,be):
    de,ops=induced('U',al,be)
    top={i:i for i in range(8) if de[i]>0}; low={i:10+i for i in range(8) if de[i]==2}   # t*e_i has index 10+i
    def lvl(i,l): return top[i] if l==0 else low[i]      # level l coordinate of factor i (l=1 means t*e_i)
    Ms=[]
    tm={top[i]:(low[i],1) for i in low}; Ms.append(tm)   # multiplication by t
    for name,o in ops:
        M={}
        for i,(j,k,sg) in o.items():
            for l in range(de[i]):           # source level l of factor i
                tl=l+k                         # target level
                if tl<de[j]: M[lvl(i,l)]=(lvl(j,tl),sg)
        Ms.append(M)
    IA=[c for i in A if de[i] for c in ([top[i]]+([low[i]] if i in low else []))]
    IB=[c for i in B if de[i] for c in ([top[i]]+([low[i]] if i in low else []))]
    return de,IA,IB,Ms
def cell_count(al,be):
    de,IA,IB,Ms=expanded(al,be)
    r=count_glue(IA,IB,Ms)
    return de,r
if __name__=='__main__':
    d=json.load(open('delta2-U.json')); out=[]; ok=True
    for n,row in enumerate(d):
        al,be=row['alpha'],row['beta']; de,r=cell_count(al,be)
        tot=sp.expand(sum(r.values())) if r else sp.Integer(0)
        obs=row['observed']; good=all(int(tot.subs(P,int(p)))==v for p,v in obs.items()); ok&=good
        # dimW over F_p -> index contribution uses length; length(G) = dim_Fp(G)
        out.append({'alpha':al,'beta':be,'by_length':{k:str(sp.factor(v)) for k,v in r.items()},'total':str(sp.factor(tot)),'observed':obs,'match':good})
        print(n,al,be,sp.factor(tot),obs,good,flush=True)
    print('BAD',BAD); print('ALL MATCH' if ok else 'SOME FAIL')
    json.dump(out,open('tmodel-U.json','w'),indent=1)
