"""Refined carry check (Grant pt216u).  For each of the 52 cells, each RREF pattern of the top A and each zero/nonzero
pattern of its free entries, decide (exactly, all odd p, via count.solve) whether the top invariance equations
T(A) in A have a solution with that pattern.  On every feasible pattern, every carry sum sum_l c_jl y_lm must have at
most one nonzero term; then Teichmueller lifts give zero carry and the Z/p^2 count equals the F_p[t]/t^2 count."""
import json, itertools, sympy as sp
from uniform import induced
from count import rref_cells, solve, P, BAD
d=json.load(open('delta2-U.json')); worst=0; report=[]; bad_cases=[]
for row in d:
    al,be=row['alpha'],row['beta']; de,ops=induced('U',al,be)
    I2=[i for i in range(8) if de[i]==2]; pos={c:t for t,c in enumerate(I2)}; n=len(I2)
    tops=[{pos[i]:(pos[j],sg) for i,(j,k,sg) in o.items() if k==0 and i in pos and j in pos} for name,o in ops]; tops=[M for M in tops if M]
    mx=0; feas=0
    for k in range(n+1):
        for piv,rows,syms in rref_cells(n,k,'y'):
            def imgs(rows):
                out=[]
                for M in tops:
                    for j,yj in enumerate(rows):
                        img=[sp.Integer(0)]*n
                        for a,(b,sg) in M.items(): img[b]+=sg*yj[a]
                        out.append((M,j,img))
                return out
            for zs in itertools.product((0,1),repeat=len(syms)):
                sub={s:0 for s,z in zip(syms,zs) if z==0}; nzs={s for s,z in zip(syms,zs) if z}
                R=[[sp.sympify(x).subs(sub) for x in r] for r in rows]
                eqs=[]
                for M,j,img in imgs(R):
                    c=[img[q] for q in piv]
                    res=[sp.expand(img[b]-sum(c[l]*R[l][b] for l in range(k))) for b in range(n)]
                    eqs+=[x for x in res if x!=0]
                cnt=solve(eqs,[],[],set(nzs),set(nzs))
                if sp.expand(cnt)==0: continue
                feas+=1
                for M,j,img in imgs(R):
                    c=[img[q] for q in piv]
                    for m in range(n):
                        t=sum(1 for l in range(k) if c[l]!=0 and R[l][m]!=0)
                        mx=max(mx,t)
                        if t>1: bad_cases.append({'alpha':al,'beta':be,'piv':list(piv),'zero_pattern':[str(s) for s in sub]})
    worst=max(worst,mx); report.append({'alpha':al,'beta':be,'I2':I2,'feasible_patterns':feas,'max_terms':mx})
print('max nonzero terms in any carry sum on a feasible pattern:',worst,'; bad cases',len(bad_cases),'; BAD',BAD)
json.dump({'max_terms':worst,'bad_cases':bad_cases,'cells':report,'bad_constants':[str(b) for b in BAD]},open('carry-U.json','w'),indent=1)
