#!/usr/bin/env python3
"""Independent arbitrary-integer cross-check of the 548-cell RLT proof."""
from pathlib import Path
import numpy as np
x=(Path(__file__).parent/'continuum-rlt-548.txt').read_text().split();at=0
def g(w=None):
 global at
 z=x[at];at+=1
 if w is not None:assert z==w,(z,w)
 return z
g('AP_CONTINUUM_RLT_V1');g('L');L=int(g());g('denom');D=int(g());g('factor_scale');R=int(g());assert L==548;n=L//2
def mat(label):
 g(label);return np.array([int(g()) for _ in range(n*n)],dtype=object).reshape(n,n)
def sym(label):
 g(label);a=np.zeros((n,n),dtype=object)
 for i in range(n):
  for j in range(i+1):a[i,j]=a[j,i]=int(g())
 return a
U,V=mat('U'),mat('V');NA,NB=sym('NA'),sym('NB');g('eta');eta=np.array([int(g()) for _ in range(n)],dtype=object)
def fac(label):
 g(label);a=np.zeros((n,n),dtype=object)
 for i in range(n):
  for j in range(i+1):a[i,j]=int(g())
 return a
Fs,Fa=fac('factor_sym'),fac('factor_anti');assert at==len(x)
cuts=[0,28,34,62,99,158,274,390,449,486,514,520,548]
s=[]
for b in range(12):
 s += ([1] if b%2==0 else [-1])*(cuts[b+1]-cuts[b])
s=np.array(s,dtype=object)
pref=np.r_[0,np.cumsum(s)]
def lf4(k):
 k=max(0,min(4*L,k));q,r=divmod(k,4)
 return 4*pref[L] if q==L else 4*pref[q]+r*s[q]
m=[];sl=[]
for i in range(L):
 z=[]
 for r in range(3):
  two=8*i+4*r;h4=lf4(two)-lf4(two-4*L)+lf4(2*i+r+2*L)-lf4(2*i+r);z.append(-s[i]*h4)
 if 2*z[1]==z[0]+z[2]:mm,cc=min(z[0],z[2]),abs(z[2]-z[0])
 else:assert z[0]==z[2];mm,cc=min(z[0],z[1]),abs(z[0]-z[1])
 assert mm%4==cc%4==0;m.append(mm//4);sl.append(cc//4)
m=np.array(m,dtype=object);sl=np.array(sl,dtype=object);assert min(m)>=0 and set(sl)=={1,2,3}
orig=np.zeros((L,L),dtype=object)
for i in range(L):
 for j in range(L):
  rr=2*i-j
  if 1<=rr<=L-2:orig[i,j]=2*s[i]*s[j]
  elif -1<=rr<=L and s[i]*s[j]<0:orig[i,j]=-2
h2=orig+orig.T
for i in range(L):h2[i,i]+=sl[i]
assert np.all(U>=0) and np.all(V>=0) and np.all(NA>=0) and np.all(NB>=0) and np.all(eta>=0)
assert np.all(np.sum(U+V,axis=1)+n*eta<=m[:n]*D)
HA=h2[:n,:n];HB=h2[:n,::-1][:,:n] # columns L-1,...,n
Ps=D*(HA+HB)-2*(NA+NB)+(U+U.T+V+V.T)+2*(eta[:,None]+eta[None,:])
Pa=D*(HA-HB)-2*NA+2*NB+(U+U.T-V-V.T)
def check(P,F):
 Q=R*R*P-2*D*(F@F.T);mar=[]
 for i in range(n):mar.append(Q[i,i]-sum(abs(Q[i,j]) for j in range(n) if i!=j))
 assert min(mar)>=0;return min(mar)
ms,ma=check(Ps,Fs),check(Pa,Fa)
score=0
for i in range(L):
 for j in range(L):
  if (i+j)%2==0:score+=2*(s[i]==s[j]==s[(i+j)//2])
  else:
   k=(i+j)//2;score+=(s[i]==s[j]==s[k])+(s[i]==s[j]==s[k+1])
assert score==128232
print('continuum RLT cross-check PASS:',ms,ma,'score',score)
