#!/usr/bin/env python3
"""
================================================================================
SRFP311T1: PART VI CANONICAL VERIFICATION ENGINE
Script: leech_twoshell_degree14_audit.py
Paper:  The Two-Shell Degree-14 Spline Engine, Higher-Order Dirichlet Vector
        Bridges, and Cuspidal Spectral Decoupling on the Leech Tangent Bundle
Author: SRFP311T1 Collaboration (October 2026)
================================================================================
"""

import time
import sympy as sp
import mpmath as mp


def run_all_audits():
    t_start = time.time()
    mp.mp.dps = 25

    print("=" * 78)
    print("SRFP311T1: PART VI CANONICAL AUDIT SUITE")
    print("The Two-Shell Degree-14 Spline Engine & Higher Dirichlet Vector Bridges")
    print("=" * 78)

    # --------------------------------------------------------------------------
    # 1. Degree-8 Master Spline P_8(x) Properties (Theorem 2.1)
    # --------------------------------------------------------------------------
    print("\n[1/5] Auditing Degree-8 Master Spline P_8(x) on [-1/2, 1/2]...")
    x = sp.Symbol('x')
    Q_inner = -1008 * x**4 + 32 * x**3 + 344 * x**2 + 136 * x + 17
    P8_poly = sp.Rational(5, 32) * ((1 - 2 * x)**4) * Q_inner

    # Boundary order at x = 1/2
    for r in range(4):
        val_r = sp.diff(P8_poly, x, r).subs(x, sp.Rational(1, 2))
        assert val_r == 0, f"Failed: derivative order {r} != 0 at x=1/2"
    val_4 = sp.diff(P8_poly, x, 4).subs(x, sp.Rational(1, 2))
    assert val_4 == 6720, f"Failed: 4th derivative {val_4} != 6720"
    print("  [PASS] Boundary orders verified: P_8^(0..3)(1/2) = 0, P_8^(4)(1/2) = 6720")

    # Symmetry and odd derivatives at x = 0
    for m in [1, 3, 5]:
        val_m = sp.diff(P8_poly, x, m).subs(x, 0)
        assert val_m == 0, f"Failed: odd derivative order {m} != 0 at x=0"
    print("  [PASS] Equatorial odd derivatives vanish identically: P_8'(0) = P_8'''(0) = P_8^(5)(0) = 0")

    # Unit normalization
    integral_P8 = 2 * sp.integrate(P8_poly, (x, 0, sp.Rational(1, 2)))
    assert integral_P8 == 1, f"Failed: total integral = {integral_P8} != 1"
    print("  [PASS] Exact unit probability normalization: integral_{-1/2}^{1/2} P_8(x) dx = 1")

    # Stratum values
    assert P8_poly.subs(x, 0) == sp.Rational(85, 32)
    assert P8_poly.subs(x, sp.Rational(1, 4)) == sp.Rational(5525, 8192)
    assert P8_poly.subs(x, sp.Rational(1, 2)) == 0
    print("  [PASS] Stratum values: P_8(0) = 85/32, P_8(+-1/4) = 5525/8192, P_8(+-1/2) = 0")

    # Strict positivity of Q_inner on [0, 1/2]
    assert Q_inner.subs(x, 0) == 17
    assert Q_inner.subs(x, sp.Rational(1, 2)) == 112
    roots_Q = sp.real_roots(Q_inner)
    assert not any(0 <= r <= 0.5 for r in roots_Q), "Failed: Q_inner has real roots in [0, 1/2]"
    print("  [PASS] Strict interior positivity: Q_inner(x) >= 17 > 0 for all x in [0, 1/2]")

    # --------------------------------------------------------------------------
    # 2. Seven-Point Bernoulli Special Value Interpolation (Theorem 2.3)
    # --------------------------------------------------------------------------
    print("\n[2/5] Auditing Seven-Point Rational Interpolant R_Master^(8)(z)...")
    z = sp.Symbol('z')
    R8_sym = -(z + 2) * (z + 4) * (z + 6) * (z - 10) * (2**z) / (30 * (z - 1) * (31 * (2**z) + 1))

    # Residue at z = 1
    res_z1 = sp.limit((z - 1) * R8_sym, z, 1)
    assert res_z1 == 1, f"Failed: residue at z=1 is {res_z1} != 1"
    print("  [PASS] Simple pole residue verified: Res_{z=1} R_Master^(8)(z) = +1")

    # 7 consecutive Bernoulli values
    bernoulli_checks = [
        (0, -sp.Rational(1, 2), "zeta(0)"),
        (-1, -sp.Rational(1, 12), "zeta(-1)"),
        (-2, 0, "zeta(-2)"),
        (-3, sp.Rational(1, 120), "zeta(-3)"),
        (-4, 0, "zeta(-4)"),
        (-5, -sp.Rational(1, 252), "zeta(-5)"),
        (-6, 0, "zeta(-6)")
    ]
    for k, val_expected, name in bernoulli_checks:
        val_eval = sp.simplify(R8_sym.subs(z, k))
        assert val_eval == val_expected, f"Failed: R8({k}) = {val_eval} != {val_expected}"
        print(f"  [PASS] k = {k:2d}: R_Master^(8)({k}) = {str(val_eval):>8} == {name}")

    # Midpoint ribbon bound at sigma = 1/2
    R8_half = float(R8_sym.subs(z, sp.Rational(1, 2)).evalf())
    zeta_half = float(sp.zeta(sp.Rational(1, 2)).evalf())
    R6_half = -1.459691726013
    assert R8_half < zeta_half < R6_half < 0
    ribbon_width = abs(R8_half - R6_half)
    print(f"  [PASS] Midpoint sandwich: {R8_half:.6f} < {zeta_half:.6f} < {R6_half:.6f}")
    print(f"         Ribbon width Delta(1/2) = {ribbon_width:.4e} < 9.43e-4")

    # --------------------------------------------------------------------------
    # 3. Closed-Form Inversion of zeta(z) via J_8(z) (Theorem 3.1)
    # --------------------------------------------------------------------------
    print("\n[3/5] Auditing Closed-Form Inversion of zeta(z) to 25 Decimal Digits...")

    def P8_num(t):
        at = abs(t)
        return (5.0 / 32.0) * ((1.0 - 2.0 * at)**4) * (-1008.0 * (t**4) + 32.0 * (at**3) + 344.0 * (t**2) + 136.0 * at + 17.0)

    def J8_func(w):
        factor = (w + 1) * (w + 3) * (w + 5) * (w + 7)
        return factor * mp.quad(lambda t: P8_num(t) * mp.hurwitz(w + 8, 1 + t), [-0.5, 0.0, 0.5])

    def K8_func(zv):
        chi_1mz = 2 * (2 * mp.pi)**(-zv) * mp.cos(mp.pi * zv / 2) * mp.gamma(zv)
        term1 = (zv + 9) * (31 * (2**zv) + 1) / (zv * (zv + 2) * (zv + 4) * (zv + 6))
        term2 = (zv - 10) * (2**(2 * zv - 1)) * (31 * (2**(1 - zv)) + 1) / (
            (1 - zv) * (3 - zv) * (5 - zv) * (7 - zv)) * chi_1mz
        return term1 + term2

    test_points = [
        mp.mpc(0.3, 14.0),
        mp.mpc(0.5, 21.022),
        mp.mpc(0.8, 30.5)
    ]
    for zv in test_points:
        num = (zv + 9) * J8_func(zv) + (zv - 10) * (2**(2 * zv - 1)) * J8_func(1 - zv)
        den = 1612800 * K8_func(zv)
        zeta_rec = num / den
        zeta_true = mp.zeta(zv)
        diff = abs(zeta_rec - zeta_true)
        assert diff < 1e-23, f"Failed at {zv}: diff = {diff}"
        print(f"  [PASS] z = {zv}: diff = {float(diff):.2e} < 1e-23")

    # --------------------------------------------------------------------------
    # 4. Pure Octant Vector Bridge for L(z, chi_{-4}) (Theorem 4.1 & 4.2)
    # --------------------------------------------------------------------------
    print("\n[4/5] Auditing Pure Octant Vector Bridge for Dirichlet Beta L(z, chi_{-4})...")

    # Combinatorial nullspace weights
    assert 245 * 1950 - 270 * 2310 + 75 * 1998 - 26 * 150 == 0, "Failed: s=16 coefficient != 0"
    assert 245 * 12480 - 270 * 11760 + 75 * 12384 - 26 * 960 == 786240, "Failed: s=8 coefficient != 786240"
    print("  [PASS] Curvature null combination [245, -270, 0, 75, -26] isolates octant diff")

    # Parameter-free integral identity check
    dirichlet_points = [2.0, 3.5, 0.5, 1.0 + 14.13j]
    for zv in dirichlet_points:
        lhs = (4**zv) * (1.0 - mp.dirichlet(zv, [0, 1, 0, -1]))
        rhs = zv * mp.quad(lambda t: mp.hurwitz(zv + 1, 1 + t), [-0.25, 0.25])
        diff = abs(lhs - rhs)
        assert diff < 1e-14, f"Failed at z={zv}: diff = {diff}"
        print(f"  [PASS] z = {zv}: 4^z(1 - L) == z * int_-0.25^0.25 zeta(z+1, 1+t) dt (diff = {float(diff):.2e} < 1e-14)")

    # Unconditional real bounds
    for sigma in [0.1, 0.5, 1.0, 2.0, 5.0]:
        L_val = float(mp.dirichlet(sigma, [0, 1, 0, -1]))
        low_bound = 1.0 - 2**(-sigma - 1)
        assert low_bound < L_val < 1.0
    print("  [PASS] Two-sided critical bounds verified: 1/2 <= 1 - 2^(-sigma-1) < L(sigma, chi_{-4}) < 1")

    # --------------------------------------------------------------------------
    # 5. Two-Shell Cusp Anomaly Cancellation (Theorem 5.1)
    # --------------------------------------------------------------------------
    print("\n[5/5] Auditing Two-Shell w = 4/85 Ramanujan Cusp Anomaly Cancellation...")
    anom_S2 = -427490120879308800
    assert sp.factorint(-anom_S2) == {2: 46, 3: 5, 5: 2}
    print("  [PASS] Single-shell spinor cusp anomaly on S_2: -2^46 * 3^5 * 5^2 verified")

    diff1_p12 = sp.Rational(345, 101384192)
    diff1x2_p12 = sp.Rational(-115, 684343296)
    assert diff1x2_p12 == -sp.Rational(4, 81) * diff1_p12
    print("  [PASS] Cross-shell 12th moment ratio: Diff_{1x2}(12) / Diff_1(12) == -4/81 == -(2/9)^2")

    anom_cross = -sp.Rational(408, 23) * (32**11) * 196560 * diff1x2_p12
    two_shell_sum = sp.Rational(4, 85) * anom_S2 + sp.Rational(81, 85) * anom_cross
    assert two_shell_sum == 0, f"Failed: two-shell sum = {two_shell_sum} != 0"
    print("  [PASS] Two-shell weighted coupling (w = 4/85 on S_2 + 81/85 on S_3): anomaly cancels to EXACT 0 in Q")

    elapsed = time.time() - t_start
    print("=" * 78)
    print(f"[OK] ALL AUDITS PASSED WITH ZERO ERRORS in {elapsed:.2f}s.")
    print("=" * 78)


if __name__ == '__main__':
    run_all_audits()