"""Exact attainment check from Shultz printed pp. 92–93; no generator import.

Run with sage -python check_geometry.py. GEOMETRY_JSON is the machine-readable
result. This validates a fitting cube, not the global optimality theorem.
"""
import numberdb.sage as numberdb
from sage.rings.rational_field import QQ
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
from sage.rings.qqbar import AA
import itertools
import json


def certificate(a):
    root2 = AA(2).sqrt()
    R = 1/a
    c = (root2*R-1)/(root2-R)
    s = (1-c*c).sqrt()
    t = (a*a-1).sqrt()
    assert 0 < c < 1 and 0 < s < 1 and t > 0
    rows = [(a/root2,a/root2,AA(0),AA(0)),
            (a*s/root2,-a*s/root2,a*c,AA(0)),
            (c*t/root2,-c*t/root2,-s*t,AA(1))]
    return rows, c, s, t


def gram_matches(rows, a):
    return all(sum(u*v for u,v in zip(r1,r2)) == (a*a if i==j else 0)
               for i,r1 in enumerate(rows) for j,r2 in enumerate(rows))


def fits(rows):
    return all(sum(abs(r[j]) for r in rows) <= 1 for j in range(4))


ring = PolynomialRing(QQ, 'z')
z = ring.gen()
p = 4*z**8 - 28*z**6 - 7*z**4 + 16*z**2 + 16
a, = [r for r in p.roots(AA, multiplicities=False) if 1 < r < QQ(11)/10]
assert p(a) == 0
rows,c,s,t = certificate(a)
gram_ok = gram_matches(rows,a)
column_ok = [sum(abs(r[j]) for r in rows)==1 for j in range(4)]
vertices = [tuple(AA(1)/2 + sum(signs[k]*rows[k][j] for k in range(3))/2
                  for j in range(4)) for signs in itertools.product((-1,1),repeat=3)]
vertices_ok = all(0 <= coordinate <= 1 for vertex in vertices for coordinate in vertex)
unit = [(AA(1),AA(0),AA(0),AA(0)),(AA(0),AA(1),AA(0),AA(0)),(AA(0),AA(0),AA(1),AA(0))]
known = gram_matches(unit,AA(1)) and fits(unit)
bad_rows = [list(row) for row in rows]
bad_rows[0][0] += QQ(1)/1000
enlarged = [tuple(v*QQ(1001)/1000 for v in row) for row in rows]
wrong_squared_rows,_,_,_ = certificate(a*a)
controls = {'perturbed_edge_gram_rejected': not gram_matches(bad_rows,a),
            'enlarged_cube_containment_rejected': not fits(enlarged),
            'squared_edge_attainment_rejected': not (gram_matches(wrong_squared_rows,a*a) and fits(wrong_squared_rows))}
failures = [] if gram_ok and all(column_ok) and vertices_ok and known and all(controls.values()) else ['Exact attainment or control failed']
result = {'checked_entries': 1,'total_entries':1,'failures':failures,
          'known_answer_control':known,'negative_control_rejected':all(controls.values()),
          'gram_equals_D_squared_identity':gram_ok,'absolute_column_sums_equal_one':column_ok,
          'all_eight_centered_vertices_in_unit_tesseract':vertices_ok,'vertices_checked':len(vertices),
          'negative_controls':controls,
          'root_approximation':str(a),'cos_beta_approximation':str(c),
          'method':'Exact AA algebra from the independently selected octic root and the manuscript edge-vector construction',
          'independence':'No generator import; direct octic selection versus generator quartic selection. Both use Sage AA. Fraction Sturm/bisection is separately implemented without Sage.',
          'limitations':'Attainment is proved by this certificate. Global optimality is the cited Shultz theorem and is not reproved here.'}
print('GEOMETRY_JSON '+json.dumps(result))
assert not failures
