#!/usr/bin/env python3
"""Complete, self-contained exact-arithmetic verification suite for:
"Peano-Kernel Instability, Exact Hessian Eigenspaces, and Gaussian--Riesz Thresholds"

Designed for Google Colab / standalone Python 3 execution.
Requires NO external libraries (uses only the Python standard library)
and performs ALL calculations strictly over Q using fractions.Fraction
(zero floating-point operations).

Verified results:
  1. [Theorem 3.1 & Corollary 4.4] Exact 8-parameter jet coefficients
     (f'(u), f''(u) at u in {2, 4, 6, 8}) and great-circle geodesic second
     variations for Riesz potentials u^{-s} (s = 1, 2, 3) on reducible
     ADE root systems (equal and unequal Coxeter numbers).
  2. [Corollary 4.2] Negative-definite transverse subspace identity for
     superposed polarizations across multiple orthogonal root components.
  3. [Lemma 5.1, Theorem 5.2, Corollary 5.4] Midpoint Peano-kernel identity,
     fourth-derivative master identity, cubic vanishing (deg <= 3), and
     quartic onset (-128*h for u^4) on Q[u] through degree 10, plus exact
     rational Riesz Peano integrals (recovering 127/432 at s = 2).
  4. [Theorem 6.1, Remark 6.2, Theorem 6.3] Certified rational enclosure
     27/40 < t_c < 17/25 for the Gaussian crossing at (h_a, h_b) = (3, 4),
     and exact Riesz threshold factorization G(s) and sign classification.
  5. [Corollary 7.5] Full 72-site Riemannian Hessian eigenvector verification
     on A_2^{12} confirming H_{u^{-2}} V = (-127/144) V.
  6. [Proposition 8.3] Internal-root alternating-hexagon certificates and
     second-difference Peano kernel for irreducible A_n (n = 4, 5, 24) and
     D_n (n = 5, 6, 24) shells, certifying -75/16 for A_24 and -1771/216 for D_24.
  7. [Proposition 8.5 & Proposition 8.6] Exact Niemeier mean-trace formula
     Tr(H_{u^{-2}}) / (23 |Phi|) = (2155 - 416*h) / 3456 and A_1^{24}
     cross-polytope spectral trace consistency.
  8. [Section 7] Full cross-factor Hessian eigenvector checks for A, D, and
     E6/E7/E8 source factors, exceptional root-cycle relations, and all 20
     reducible rooted Niemeier eigenspace multiplicity bounds.
"""

from collections import defaultdict
from fractions import Fraction as F
from itertools import combinations
from math import factorial


# ==============================================================================
# 0. Exact Linear Algebra & Root System Builders over Z / Q
# ==============================================================================

def dot(u, v):
    return sum(x * y for x, y in zip(u, v))


def sub(u, v):
    return tuple(x - y for x, y in zip(u, v))


def root_system(kind, n):
    """Build standard integer-coordinate roots of A_n (in Z^{n+1}) or D_n (in Z^n)
    normalized to squared norm ||x||^2 = 2.
    """
    N = n + 1 if kind == "A" else n
    roots = []
    for i, j in combinations(range(N), 2):
        for t in (1, -1) if kind == "D" else (-1,):
            for sign in (1, -1):
                r = [0] * N
                r[i] = sign
                r[j] = sign * t
                roots.append(tuple(r))
    return roots


def direct_sum_roots(factors):
    """Build orthogonal direct sum of root systems."""
    total_dim = sum(len(r[0]) for r in factors)
    all_roots = []
    offset = 0
    for comp_idx, roots in enumerate(factors):
        dim = len(roots[0])
        for r in roots:
            vec = [0] * offset + list(r) + [0] * (total_dim - offset - dim)
            all_roots.append((comp_idx, tuple(vec)))
        offset += dim
    return all_roots, total_dim


# ==============================================================================
# 1. Section 3 & 4: Universal Hexagon Identity & Geodesic Second Variation
# ==============================================================================

def check_jet_coefficients(n_a, n_b):
    """Verify the 8 jet coefficients f'(u), f''(u) at u in {2,4,6,8} for A_{n_a} (+) A_{n_b}."""
    roots_a = root_system("A", n_a)
    roots_b = root_system("A", n_b)
    phi, dim = direct_sum_roots([roots_a, roots_b])
    dim_a = n_a + 1

    unit = lambda i: tuple(int(j == i) for j in range(dim))
    p = sub(unit(0), unit(1))
    q = sub(unit(1), unit(2))
    r = sub(unit(2), unit(0))
    w = sub(unit(dim_a), unit(dim_a + 1))

    H = {
        p: 1,
        q: 1,
        r: 1,
        tuple(-x for x in p): -1,
        tuple(-x for x in q): -1,
        tuple(-x for x in r): -1,
    }
    root_vecs = set(vec for _, vec in phi)
    assert all(x in root_vecs for x in H)
    assert dot(w, w) == 2 and all(dot(x, w) == 0 for x in H)

    fp = defaultdict(F)
    fpp = defaultdict(F)
    norm_sq = F(6 * dot(w, w))

    for i, (_, x) in enumerate(phi):
        for j in range(i + 1, len(phi)):
            _, y = phi[j]
            sx = H.get(x, 0)
            sy = H.get(y, 0)
            if sx == 0 and sy == 0:
                continue
            u = 4 - 2 * dot(x, y)
            dxy = sub(x, y)
            fp[u] += F(
                (2 - F(u, 2)) * (sx * sx + sy * sy) * dot(w, w)
                - 4 * sx * sy * dot(w, w),
                norm_sq,
            )
            fpp[u] += F(4 * (sx - sy) ** 2 * (dot(dxy, w) ** 2), norm_sq)

    h_a = n_a + 1
    h_b = n_b + 1
    assert fp[2] == 2 * h_a and fp[6] == -2 * h_a and fp[4] == 0 and fp[8] == 0
    assert fpp[4] == 8 * h_b and fpp[2] == 0 and fpp[6] == 0 and fpp[8] == 0
    return dict(fp), dict(fpp)


def geodesic_second_variation_riesz(n_a, n_b, s):
    """Differentiate E_f along exact rational great-circle 2-jets for f(u) = u^{-s}."""
    roots_a = root_system("A", n_a)
    roots_b = root_system("A", n_b)
    phi, dim = direct_sum_roots([roots_a, roots_b])
    dim_a = n_a + 1

    unit = lambda i: tuple(int(j == i) for j in range(dim))
    p = sub(unit(0), unit(1))
    q = sub(unit(1), unit(2))
    r = sub(unit(2), unit(0))
    w = sub(unit(dim_a), unit(dim_a + 1))

    H = {
        p: 1,
        q: 1,
        r: 1,
        tuple(-x for x in p): -1,
        tuple(-x for x in q): -1,
        tuple(-x for x in r): -1,
    }

    def f_d1(u0):
        return F(-s, u0 ** (s + 1))

    def f_d2(u0):
        return F(s * (s + 1), u0 ** (s + 2))

    E_t1 = F(0)
    E_t2_twice = F(0)
    ww = dot(w, w)

    for i in range(len(phi)):
        _, x = phi[i]
        sx = H.get(x, 0)
        for j in range(i + 1, len(phi)):
            _, y = phi[j]
            sy = H.get(y, 0)
            if sx == 0 and sy == 0:
                continue
            dxy = sub(x, y)
            u0 = dot(dxy, dxy)
            u1 = 2 * (sx - sy) * dot(dxy, w)
            # Great-circle acceleration x''(0) = -||v_x||^2 x / 2
            u2 = 2 * ((sx - sy) ** 2) * ww - dot(
                dxy,
                tuple(sx * sx * ww * xi - sy * sy * ww * yi for xi, yi in zip(x, y)),
            )
            E_t1 += f_d1(u0) * u1
            E_t2_twice += f_d2(u0) * (u1 ** 2) + f_d1(u0) * u2

    assert E_t1 == 0, f"Stationarity failed: E_t1={E_t1}"
    rayleigh = E_t2_twice / F(6 * ww)

    h_a = n_a + 1
    h_b = n_b + 1
    expected = F(s, 4 ** s) * (
        F(h_b * (s + 1), 2) - F(h_a * (2 ** s)) * (F(1) - F(1, 3 ** (s + 1)))
    )
    assert rayleigh == expected, (rayleigh, expected)
    return rayleigh


def check_superposed_polarization():
    """Verify Corollary 4.2 for a superposed polarization across orthogonal components."""
    roots_a = root_system("A", 3)   # A_3, h_a = 4
    roots_b1 = root_system("A", 2)  # A_2, h_1 = 3
    roots_b2 = root_system("A", 1)  # A_1, h_2 = 2
    phi, dim = direct_sum_roots([roots_a, roots_b1, roots_b2])

    unit = lambda i: tuple(int(j == i) for j in range(dim))
    p = sub(unit(0), unit(1))
    q = sub(unit(1), unit(2))
    r = sub(unit(2), unit(0))
    w1 = sub(unit(4), unit(5))
    w2 = tuple(2 * x for x in sub(unit(7), unit(8)))
    w = tuple(x + y for x, y in zip(w1, w2))

    H = {
        p: 1,
        q: 1,
        r: 1,
        tuple(-x for x in p): -1,
        tuple(-x for x in q): -1,
        tuple(-x for x in r): -1,
    }

    f_d1 = lambda u: F(-2, u ** 3)
    f_d2 = lambda u: F(6, u ** 4)

    Q_val = F(0)
    for i in range(len(phi)):
        _, x = phi[i]
        sx = H.get(x, 0)
        for j in range(i + 1, len(phi)):
            _, y = phi[j]
            sy = H.get(y, 0)
            if sx == 0 and sy == 0:
                continue
            dxy = sub(x, y)
            u = dot(dxy, dxy)
            Q_val += 4 * f_d2(u) * ((sx - sy) ** 2) * (dot(dxy, w) ** 2)
            Q_val += (
                f_d1(u)
                * ((2 - F(u, 2)) * (sx * sx + sy * sy) - 4 * sx * sy)
                * dot(w, w)
            )

    lhs = Q_val / F(6)
    rhs = (
        2 * 4 * (f_d1(2) - f_d1(6)) * dot(w, w)
        + 8 * f_d2(4) * (3 * dot(w1, w1) + 2 * dot(w2, w2))
    )
    assert lhs == rhs and lhs < 0, (lhs, rhs)
    return lhs


# ==============================================================================
# 2. Section 5: Peano-Kernel Identities on Q[u] & Exact Riesz Integrals
# ==============================================================================

def poly_deriv(coeffs, order=1):
    res = [F(c) for c in coeffs]
    for _ in range(order):
        res = [i * res[i] for i in range(1, len(res))]
    return res if res else [F(0)]


def poly_eval(coeffs, x):
    x = F(x)
    return sum(F(c) * (x ** i) for i, c in enumerate(coeffs))


def poly_mul(p, q):
    res = [F(0)] * (len(p) + len(q) - 1)
    for i, a in enumerate(p):
        for j, b in enumerate(q):
            res[i + j] += F(a) * F(b)
    return res


def poly_def_int(coeffs, a, b):
    a, b = F(a), F(b)
    return sum(F(c, i + 1) * (b ** (i + 1) - a ** (i + 1)) for i, c in enumerate(coeffs))


def peano_integral_sq(f4_coeffs):
    """Exact integral int_2^6 rho(u)^2 f^{(4)}(u) du for polynomial f^{(4)}."""
    rho_left_sq = [F(4), F(-4), F(1)]    # (u - 2)^2
    rho_right_sq = [F(36), F(-12), F(1)]  # (6 - u)^2
    return (
        poly_def_int(poly_mul(rho_left_sq, f4_coeffs), 2, 4)
        + poly_def_int(poly_mul(rho_right_sq, f4_coeffs), 4, 6)
    )


def peano_integral_lin(f4_coeffs):
    """Exact integral int_2^6 rho(u) f^{(4)}(u) du for polynomial f^{(4)}."""
    rho_left = [F(-2), F(1)]   # u - 2
    rho_right = [F(6), F(-1)]  # 6 - u
    return (
        poly_def_int(poly_mul(rho_left, f4_coeffs), 2, 4)
        + poly_def_int(poly_mul(rho_right, f4_coeffs), 4, 6)
    )


def riesz_peano_integral_sq(s):
    """Exact rational integral int_2^6 rho(u)^2 f_s^{(4)}(u) du for f_s(u) = u^{-s}."""
    c4 = F(s * (s + 1) * (s + 2) * (s + 3))
    int_u_neg_m = lambda m, a, b: (F(1, a ** (m - 1)) - F(1, b ** (m - 1))) / F(m - 1)
    left = (
        int_u_neg_m(s + 2, 2, 4)
        - 4 * int_u_neg_m(s + 3, 2, 4)
        + 4 * int_u_neg_m(s + 4, 2, 4)
    )
    right = (
        int_u_neg_m(s + 2, 4, 6)
        - 12 * int_u_neg_m(s + 3, 4, 6)
        + 36 * int_u_neg_m(s + 4, 4, 6)
    )
    return c4 * (left + right)


def verify_peano_identities():
    """Verify Lemma 5.1, Theorem 5.2, Corollary 5.4, and Eq. (8.3) in Q."""
    assert peano_integral_sq([F(1)]) == F(16, 3)
    assert peano_integral_lin([F(1)]) == F(4)

    for deg in range(11):
        f = [F(0)] * deg + [F(1)]
        f1 = poly_deriv(f, 1)
        f2 = poly_deriv(f, 2)
        f4 = poly_deriv(f, 4)

        # Lemma 5.1 (Midpoint Peano kernel)
        assert poly_def_int(f2, 2, 6) - 4 * poly_eval(f2, 4) == F(1, 2) * peano_integral_sq(f4)
        # Second-difference Peano kernel
        lhs_diff2 = poly_eval(f2, 2) - 2 * poly_eval(f2, 4) + poly_eval(f2, 6)
        assert lhs_diff2 == peano_integral_lin(f4)

        # Theorem 5.2 & Corollary 5.4
        for h_a, h_b in [(3, 3), (4, 4), (3, 2), (3, 5), (25, 25)]:
            R_direct = 2 * h_a * (poly_eval(f1, 2) - poly_eval(f1, 6)) + 8 * h_b * poly_eval(f2, 4)
            R_peano = -8 * (h_a - h_b) * poly_eval(f2, 4) - h_a * peano_integral_sq(f4)
            assert R_direct == R_peano
            if h_a == h_b and deg <= 3:
                assert R_direct == 0
            if h_a == h_b and deg == 4:
                assert R_direct == -128 * h_a

        # Proposition 8.3 (Internal-root Peano identity)
        for h, c in [(5, 8), (25, 8), (8, 16), (46, 16)]:
            R_int_direct = (
                2 * h * (poly_eval(f1, 2) - poly_eval(f1, 6))
                + 8 * h * poly_eval(f2, 4)
                + c * lhs_diff2
            )
            R_int_peano = -h * peano_integral_sq(f4) + c * peano_integral_lin(f4)
            assert R_int_direct == R_int_peano

    for s in (1, 2, 3, 4):
        peano_val = riesz_peano_integral_sq(s)
        f1 = lambda u: F(-s, u ** (s + 1))
        f2 = lambda u: F(s * (s + 1), u ** (s + 2))
        for h_a, h_b in [(3, 3), (4, 4), (5, 5), (3, 2), (4, 3)]:
            R_direct = 2 * h_a * (f1(2) - f1(6)) + 8 * h_b * f2(4)
            R_peano = -8 * (h_a - h_b) * f2(4) - h_a * peano_val
            assert R_direct == R_peano
    assert riesz_peano_integral_sq(2) == F(127, 432)


# ==============================================================================
# 3. Section 6: Gaussian Enclosure & Riesz Coxeter-Ratio Thresholds
# ==============================================================================

def partial_sinh_over_x(x):
    return F(1) + x * x / factorial(3) + x ** 4 / factorial(5)


def upper_sinh_over_x(x):
    assert F(0) < x * x < 72
    return partial_sinh_over_x(x) + x ** 6 / factorial(7) / (1 - x * x / F(72))


def G_riesz(s):
    assert isinstance(s, int) and s >= 0
    return (F(2) ** (s + 1) - F(2, 3) ** (s + 1)) / (s + 1)


def verify_thresholds():
    """Verify Remark 6.2 Gaussian bracket and Theorem 6.3 Riesz crossing formula."""
    low, high = F(27, 40), F(17, 25)
    xlo, xhi = 2 * low, 2 * high
    target = F(4, 3)
    gap_lo = target - upper_sinh_over_x(xlo)
    gap_hi = partial_sinh_over_x(xhi) - target
    assert gap_lo > 0 and gap_hi > 0

    assert G_riesz(0) == F(4, 3)
    assert G_riesz(1) == F(16, 9)
    assert all(G_riesz(s + 1) > G_riesz(s) for s in range(20))

    for ha, hb in [(3, 3), (3, 4), (4, 5), (3, 5), (3, 6), (5, 3), (6, 8)]:
        ratio = F(hb, ha)
        for s in range(1, 16):
            direct = F(s) * F(1, 4) ** s * (
                F(hb * (s + 1), 2) - ha * F(2) ** s * (1 - F(1, 3) ** (s + 1))
            )
            factored = F(ha * s * (s + 1), 2) * F(1, 4) ** s * (ratio - G_riesz(s))
            assert direct == factored
            assert (direct > 0) == (ratio > G_riesz(s))
            assert (direct < 0) == (ratio < G_riesz(s))
            if ratio <= F(4, 3):
                assert direct < 0

    assert G_riesz(0) < F(5, 3) < G_riesz(1)
    return gap_lo, gap_hi


# ==============================================================================
# 4. Section 7: Full Hessian Eigenvector Verification on A_2^{12}
# ==============================================================================

def verify_a2_12_eigenvector():
    """Verify Corollary 7.5: H_{u^{-2}} V = (-127/144) V across all 72 roots of A_2^{12}."""
    m = 12
    factors = [root_system("A", 2) for _ in range(m)]
    phi, dim = direct_sum_roots(factors)
    assert len(phi) == 72 and dim == 36

    unit = lambda i: tuple(int(j == i) for j in range(dim))
    p = sub(unit(0), unit(1))
    q = sub(unit(1), unit(2))
    r = sub(unit(2), unit(0))
    w = sub(unit(3), unit(4))  # Polarize into second A_2 factor

    H = {
        p: 1,
        q: 1,
        r: 1,
        tuple(-x for x in p): -1,
        tuple(-x for x in q): -1,
        tuple(-x for x in r): -1,
    }

    f_d1 = lambda u: F(-2, u ** 3)
    f_d2 = lambda u: F(6, u ** 4)
    expected_lambda = F(-127, 144)

    for _, x in phi:
        vx = tuple(H.get(x, 0) * wi for wi in w)
        amb = [F(0)] * dim
        for _, y in phi:
            if y == x:
                continue
            vy = tuple(H.get(y, 0) * wi for wi in w)
            dxy = sub(x, y)
            u = dot(dxy, dxy)
            c1 = (2 - F(u, 2)) * f_d1(u)
            c2 = -2 * f_d1(u)
            c3 = 4 * f_d2(u) * dot(dxy, sub(vx, vy))
            for k in range(dim):
                amb[k] += c1 * vx[k] + c2 * vy[k] + c3 * dxy[k]
        ip_ax = sum(amb[k] * x[k] for k in range(dim))
        proj = tuple(amb[k] - F(ip_ax, 2) * x[k] for k in range(dim))
        target = tuple(expected_lambda * vxi for vxi in vx)
        assert proj == target, (x, proj, target)

    return expected_lambda


# ==============================================================================
# 5. Section 8: Internal-Root Certificates (A_n, D_n), Mean Trace & A_1^{24}
# ==============================================================================

def count_internal_coeffs(kind, n):
    """Audit exact f'(u), f''(u) coefficients for Proposition 8.3."""
    roots = root_system(kind, n)
    N = len(roots[0])
    unit = lambda i: tuple(int(j == i) for j in range(N))
    p = sub(unit(0), unit(1))
    q = sub(unit(1), unit(2))
    r = sub(unit(2), unit(0))
    w = sub(unit(3), unit(4))
    H = {
        p: 1,
        q: 1,
        r: 1,
        tuple(-t for t in p): -1,
        tuple(-t for t in q): -1,
        tuple(-t for t in r): -1,
    }
    root_set = set(roots)
    assert all(x in root_set for x in H) and dot(w, w) == 2 and all(dot(w, x) == 0 for x in H)

    fp = defaultdict(F)
    fpp = defaultdict(F)
    for x in H:
        for y in roots:
            if y == x:
                continue
            if y in H and x > y:
                continue
            u = 4 - 2 * dot(x, y)
            vx = H[x]
            vy = H.get(y, 0)
            fp[u] += F(2 * ((2 - F(u, 2)) * (vx * vx + vy * vy) - 4 * vx * vy), 12)
            fpp[u] += F(4 * (vx - vy) ** 2 * (dot(sub(x, y), w)) ** 2, 12)
    return dict(fp), dict(fpp), len(roots)


def verify_internal_and_niemeier():
    """Verify Propositions 8.3, 8.5, and 8.6 in exact rational arithmetic."""
    expected_R2 = {
        ("A", 4): F(515, 432),
        ("A", 5): F(97, 108),
        ("A", 24): F(-75, 16),
        ("D", 5): F(107, 36),
        ("D", 6): F(515, 216),
        ("D", 24): F(-1771, 216),
    }
    results = []
    fprime = lambda u: -2 * F(1, u ** 3)
    fsecond = lambda u: 6 * F(1, u ** 4)

    for kind, ns in [("A", [4, 5, 24]), ("D", [5, 6, 24])]:
        for n in ns:
            fp, fpp, count = count_internal_coeffs(kind, n)
            h = n + 1 if kind == "A" else 2 * n - 2
            c = 8 if kind == "A" else 16
            assert (
                fp.get(2, F(0)) == 2 * h
                and fp.get(6, F(0)) == -2 * h
                and all(fp.get(u, F(0)) == 0 for u in (4, 8))
            )
            assert (
                fpp.get(2, F(0)) == c
                and fpp.get(4, F(0)) == 8 * h - 2 * c
                and fpp.get(6, F(0)) == c
                and fpp.get(8, F(0)) == 0
            )
            val = sum(k * fprime(u) for u, k in fp.items()) + sum(
                k * fsecond(u) for u, k in fpp.items()
            )
            formula_val = F(-127 * h, 432) + F(575 * c, 1728)
            assert val == formula_val == expected_R2[(kind, n)]
            results.append((f"{kind}_{n}", count, h, c, val))

    # Proposition 8.5: Niemeier trace formula
    bracket = lambda c: 23 * c * fprime(4 - 2 * c) + 4 * (2 - F(c * c, 2)) * fsecond(4 - 2 * c)
    assert bracket(1) == F(-7, 2)
    assert bracket(0) == F(3, 16)
    assert bracket(-1) == F(13, 54)
    assert bracket(-2) == F(23, 128)
    for h in (2, 3, 4, 5, 6, 25, 46):
        tr_per_root = (
            2 * (h - 2) * (bracket(1) + bracket(-1))
            + (20 * h + 6) * bracket(0)
            + bracket(-2)
        )
        assert tr_per_root / F(23) == F(2155 - 416 * h, 3456)

    # Proposition 8.6: Cross-polytope A_1^{24} spectrum and trace consistency
    # Eigenvalues: 0^(276), (17/64)^(528), (3/4)^(276), (201/64)^(24)
    a1_dim = 276 + 528 + 276 + 24
    assert a1_dim == 48 * 23  # 1104 tangent dimensions
    a1_trace = 276 * F(0) + 528 * F(17, 64) + 276 * F(3, 4) + 24 * F(201, 64)
    a1_mean_from_spec = a1_trace / F(1104)
    a1_mean_from_prop84 = F(2155 - 416 * 2, 3456)
    assert a1_mean_from_spec == a1_mean_from_prop84 == F(49, 128)

    return results


# ==============================================================================
# Main Execution Suite
# ==============================================================================

def main_original():
    print("=" * 74)
    print("EXACT RATIONAL VERIFICATION SUITE (fractions.Fraction ONLY, ZERO FLOATS)")
    print("=" * 74)

    print("\n[1] Theorem 3.1, Corollary 4.2 & Corollary 4.4 (Jet & Geodesic Checks):")
    for n_a, n_b in [(2, 2), (3, 3), (4, 4), (2, 1), (2, 3)]:
        check_jet_coefficients(n_a, n_b)
        r_vals = {s: geodesic_second_variation_riesz(n_a, n_b, s) for s in (1, 2, 3)}
        print(
            f"  A_{n_a} (+) A_{n_b} (h_a={n_a+1}, h_b={n_b+1}): "
            f"R_1={r_vals[1]}, R_2={r_vals[2]}, R_3={r_vals[3]}"
        )
    sup_val = check_superposed_polarization()
    print(f"  Superposed transverse polarization (A_3 -> A_2 (+) A_1): Q_2/6 = {sup_val} < 0")

    print("\n[2] Lemma 5.1, Theorem 5.2 & Corollary 5.4 (Peano Kernel Identities):")
    verify_peano_identities()
    print("  Midpoint & 2nd-difference Peano identities verified on Q[u] (deg 0..10).")
    print("  Cubic vanishing (deg <= 3) and quartic onset (-128*h) verified.")
    print(f"  Exact Riesz Peano integral at s=2: {riesz_peano_integral_sq(2)} (matches 127/432).")

    print("\n[3] Theorem 6.1, Remark 6.2 & Theorem 6.3 (Gaussian & Riesz Thresholds):")
    gap_lo, gap_hi = verify_thresholds()
    print("  Gaussian root enclosure for (h_a, h_b)=(3, 4): 27/40 < t_c < 17/25")
    print(f"    Exact rational gap at 27/40: {gap_lo}")
    print(f"    Exact rational gap at 17/25: {gap_hi}")
    print("  Riesz threshold G(s) factorization and sign dichotomy at r = 4/3 verified.")

    print("\n[4] Corollary 7.5 (Full 72-Root Hessian Eigenvector on A_2^{12}):")
    eig_val = verify_a2_12_eigenvector()
    print(f"  Verified H_{{u^-2}} V = ({eig_val}) V across all 72 sites in R^36.")

    print("\n[5] Propositions 8.3, 8.5 & 8.6 (Internal Hexagon Modes & Niemeier Shells):")
    int_results = verify_internal_and_niemeier()
    for name, count, h, c, val in int_results:
        print(f"  {name:4s}: |Phi|={count:4d}, h={h:2d}, c={c:2d} => R_2(V(w)) = {val}")
    print("  Niemeier mean trace verified; A_1^24 claimed spectrum passes dimension and trace checks.")

    print("\n" + "=" * 74)
    print("ALL VERIFICATIONS PASSED USING EXACT RATIONAL ARITHMETIC.")
    print("=" * 74)

# ======== SPECTRAL-REVISION SUPPLEMENT (FULL-HESSIAN ACTION) ========

# Exact rational checks for the cross-factor Hessian eigenspace theorem.
# No nonstandard dependencies and no floating-point arithmetic.
from fractions import Fraction as F
from itertools import combinations
from collections import deque


def cartan_e(rank):
    assert rank in (6, 7, 8)
    # Dynkin diagram: chain 0--1--...--(rank-2), with terminal
    # vertex rank-1 joined to vertex 2. Its arms have lengths
    # 2, rank-4, 1, yielding E6, E7, E8 respectively.
    n = rank
    edges = [(i, i + 1) for i in range(n - 2)] + [(2, n - 1)]
    g = [[2 if i == j else 0 for j in range(n)] for i in range(n)]
    for i, j in edges:
        g[i][j] = g[j][i] = -1
    return g


def gram_dot(u, v, gram):
    return sum(u[i] * gram[i][j] * v[j] for i in range(len(u)) for j in range(len(v)) if u[i] and v[j] and gram[i][j])


def roots_e(rank):
    gram = cartan_e(rank)
    seen = set()
    q = deque()
    for i in range(rank):
        for s in (-1, 1):
            x = tuple(s if j == i else 0 for j in range(rank))
            seen.add(x)
            q.append(x)
    while q:
        x = q.popleft()
        for i in range(rank):
            xi = list(x)
            xi[i] -= sum(gram[i][j] * x[j] for j in range(rank))
            y = tuple(xi)
            if y not in seen:
                seen.add(y)
                q.append(y)
    target = {6: 72, 7: 126, 8: 240}[rank]
    assert len(seen) == target
    assert all(gram_dot(x, x, gram) == 2 for x in seen)
    return sorted(seen), gram


def roots_a(n):
    d = n + 1
    roots = []
    for i, j in combinations(range(d), 2):
        r = tuple((1 if k == i else -1 if k == j else 0) for k in range(d))
        roots.extend([r, tuple(-t for t in r)])
    return roots, [[int(i == j) for j in range(d)] for i in range(d)]


def roots_d(n):
    d = n
    roots = []
    for i, j in combinations(range(d), 2):
        for s in (-1, 1):
            v = tuple((1 if k == i else s if k == j else 0) for k in range(d))
            roots.extend([v, tuple(-t for t in v)])
    return roots, [[int(i == j) for j in range(d)] for i in range(d)]


def source(kind, n):
    if kind == 'A': return roots_a(n)
    if kind == 'D': return roots_d(n)
    if kind == 'E': return roots_e(n)
    raise ValueError(kind)


def product_system(factors):
    items = [source(*factor) for factor in factors]
    dim = sum(len(mat) for _roots, mat in items)
    gram = [[0 for _ in range(dim)] for _ in range(dim)]
    roots = []
    offsets = []
    offset = 0
    for a, (rs, mat) in enumerate(items):
        offsets.append(offset)
        r = len(mat)
        for i in range(r):
            for j in range(r):
                gram[offset + i][offset + j] = mat[i][j]
        for x in rs:
            roots.append((a, (0,)*offset + x + (0,)*(dim-offset-r)))
        offset += r
    return roots, gram, offsets, items


def get_cycle(rs, gram):
    S = set(rs)
    for p in rs:
        for q in rs:
            if gram_dot(p, q, gram) != -1:
                continue
            r = tuple(-a-b for a,b in zip(p,q))
            if r in S:
                c = {z: F(1) for z in (p,q,r)}
                c.update({tuple(-t for t in z): F(-1) for z in (p,q,r)})
                assert sum(c.values()) == 0
                assert all(sum(k*vec[i] for vec,k in c.items()) == 0 for i in range(len(p)))
                return c
    raise AssertionError('no A2 triple')


def test_full_action(factors, s=2, extra_cycle=True):
    roots, gram, offsets, items = product_system(factors)
    source_roots, source_gram = items[0]
    c0 = get_cycle(source_roots, source_gram)
    c = c0.copy()
    # A second signed cycle gives a general non-six-site element of the kernel.
    if extra_cycle:
        # Use any Weyl reflected copy that is not +/- original.
        if factors[0][0] == 'E':
            candidates = []
            for i in range(len(source_gram)):
                reflected = {}
                for x, coefficient in c0.items():
                    y = list(x)
                    y[i] -= sum(source_gram[i][j] * x[j] for j in range(len(x)))
                    reflected[tuple(y)] = coefficient
                candidates.append(reflected)
        else:
            candidates = []
            for p in source_roots:
                reflected = {}
                for x, coefficient in c0.items():
                    # s_p(x)=x-(x.p)*p, for ||p||^2=2.
                    xp = gram_dot(x, p, source_gram)
                    y = tuple(x[i]-xp*p[i] for i in range(len(x)))
                    reflected[y] = coefficient
                candidates.append(reflected)
        for d in candidates:
            if d != c0 and d != {x:-v for x,v in c0.items()}:
                for x,v in d.items(): c[x] = c.get(x,F(0)) + v
                break
    assert all(c.get(tuple(-t for t in x),F(0)) == -v for x,v in c.items())
    assert all(sum(k*x[j] for x,k in c.items()) == 0 for j in range(len(source_roots[0])))
    b_roots, b_gram = items[1]
    w0 = b_roots[0]
    w = (0,)*offsets[1] + w0 + (0,)*(len(gram)-offsets[1]-len(w0))
    assert gram_dot(w,w,gram) == 2
    V = [(c.get(x[offsets[0]:offsets[0]+len(source_gram)],F(0)) if a == 0 else F(0)) for a,x in roots]
    fp = lambda u: -F(s,u**(s+1))
    fpp = lambda u: F(s*(s+1),u**(s+2))
    def coxeter(k,n):
        if k=='A': return n+1
        if k=='D': return 2*n-2
        return {6:12,7:18,8:30}[n]
    ha=coxeter(*factors[0])
    hb=coxeter(*factors[1])
    lam = 2*ha*(fp(2)-fp(6))+8*hb*fpp(4)
    for i,(_a,x) in enumerate(roots):
        vx = V[i]
        ambient = [F(0)]*len(x)
        for j,(_b,y) in enumerate(roots):
            if i==j: continue
            vy=V[j]
            dxy = tuple(x[k]-y[k] for k in range(len(x)))
            u=4-2*gram_dot(x,y,gram)
            ds = gram_dot(dxy,w,gram)*(vx-vy)
            t1=(2-F(u,2))*fp(u)*vx
            t2=-2*fp(u)*vy
            t3=4*fpp(u)*ds
            for k in range(len(x)):
                ambient[k]+=(t1+t2)*w[k]+t3*dxy[k]
        proj_scale=gram_dot(ambient,x,gram)/F(2)
        projection=tuple(ambient[k]-proj_scale*x[k] for k in range(len(x)))
        expected=tuple(lam*vx*w[k] for k in range(len(x)))
        assert projection==expected,(factors,i,projection,expected)
    return lam,len(roots),sum(bool(v) for v in V)


def verify_e_root_relations():
    for n in (6,7,8):
        roots,gram=roots_e(n)
        positive={x for x in roots if all(t>=0 for t in x)}
        simple={tuple(int(i==j) for j in range(n)) for i in range(n)}
        assert len(positive)==len(roots)//2
        assert simple <= positive
        for beta in positive-simple:
            assert any(tuple(beta[j]-int(j==i) for j in range(n)) in positive
                       for i in range(n)),(n,beta)
        assert len(positive)-n == n*({6:12,7:18,8:30}[n]-2)//2
    return True


def verify_niemeier_table():
    data=[('A2^12',3,[2]*12,264),('A3^8',4,[3]*8,504),('A4^6',5,[4]*6,720),
          ('A5^4D4',6,[5]*4+[4],920),('D4^6',6,[4]*6,960),('A6^4',7,[6]*4,1080),
          ('A7^2D5^2',8,[7]*2+[5]*2,1284),('A8^3',9,[8]*3,1344),
          ('A9^2D6',10,[9]*2+[6],1512),('D6^4',10,[6]*4,1728),
          ('E6^4',12,[6]*4,2160),('A11D7E6',12,[11,7,6],1850),
          ('A12^2',13,[12]*2,1584),('D8^3',14,[8]*3,2304),
          ('A15D9',16,[15,9],1890),('A17E7',18,[17,7],1904),
          ('D10E7^2',18,[10,7,7],3024),('D12^2',22,[12]*2,2880),
          ('D16E8',30,[16,8],3584),('E8^3',30,[8]*3,5376)]
    for label,h,ranks,expected in data:
        assert sum(ranks)==24
        got=F(h-2,2)*(24*24-sum(r*r for r in ranks))
        assert got.denominator==1 and got==expected,(label,got,expected)
    return len(data)


def main_spectral():
    verify_e_root_relations()
    print('E6, E7, E8 positive-root height-reduction cycle relations: PASS')
    tests=[ [('A',2),('A',2)], [('A',3),('A',2)], [('A',4),('D',4)],
            [('D',4),('A',2)], [('D',5),('A',1)], [('E',6),('A',1)],
            [('E',7),('A',1)], [('E',8),('A',1)] ]
    for factors in tests:
        eigen,n,sites=test_full_action(factors)
        print(f'{factors}: full {n}-site exact eigenvector identity PASS; eigenvalue={eigen}; moving sites={sites}')
    total=verify_niemeier_table()
    print(f'{total} Niemeier multiplicity entries verified in rational arithmetic: PASS')
    print('ALL NEW EXACT EIGENMODE CHECKS PASSED')

if __name__ == "__main__":
    main_original()
    main_spectral()
