#!/usr/bin/env python3
"""Independent exact Python cross-check of the SDP lower certificate."""
from fractions import Fraction
from pathlib import Path

xs = (Path(__file__).parent / "sdp-l256.txt").read_text().split()
at = 0
def take(want=None):
    global at
    x=xs[at]; at+=1
    if want is not None: assert x==want,(x,want)
    return x

take("AP_SDP_LOWER_V1"); take("L"); L=int(take())
take("denom"); D=int(take()); take("factor_scale"); R=int(take())
take("diag"); diag=[int(take()) for _ in range(L)]
take("factor"); P=[[0]*L for _ in range(L)]
for i in range(L):
    for j in range(i+1): P[i][j]=int(take())
take("claimed_diag_sum"); S=int(take())
take("claimed_bound"); num=int(take()); den=int(take())
assert at==len(xs) and sum(diag)==S

def ae(i0,j0):
    i,j=i0+1,j0+1
    return int(j+1<=2*i<=j+L)+int(i+1<=2*j<=i+L)

margins=[]
for i in range(L):
    radius=0
    for j in range(L):
        dot=sum(P[i][k]*P[j][k] for k in range(min(i,j)+1))
        c=D*ae(i,j)+(diag[i] if i==j else 0)
        e=R*R*c-D*dot
        if i==j: diagonal=e
        else: radius+=abs(e)
    margins.append(diagonal-radius)
assert min(margins)>=0
bound=Fraction(1,16)-Fraction(1,8*L)-Fraction(S,8*D*L*L)
assert bound==Fraction(num,den)
assert bound>Fraction(1675,32768)
print(f"SDP cross-check PASS: min margin {min(margins)}, bound {bound}")
