"""
verify_P144.py — Verification script for Addendum 144: Uniqueness of alpha^{-1}
A Choice-Point Analysis of the (B^4, S^3) Derivation.
L. F. Vlegels, LumenOS TOE corpus.

Verifies the numerical claims in §§ 1–4, focusing on CP-3 (flat vs. natural
B^4 volume measure) as the deepest structural gap identified.

Run:
    python verify_P144.py
"""

import math
import sys
import numpy as np
from numpy.polynomial.legendre import leggauss


def quad(f, a, b, n=200):
    """
    Gauss-Legendre quadrature on [a, b].
    Exact for polynomials of degree ≤ 2n−1.  n=200 gives ~400-point rule,
    more than sufficient for the smooth polynomial integrands here.
    Returns (result, estimated_error_bound).
    """
    xi, wi = leggauss(n)
    # transform from [−1,1] to [a,b]
    x_mapped = 0.5 * (b - a) * xi + 0.5 * (b + a)
    result = 0.5 * (b - a) * float(np.dot(wi, np.vectorize(f)(x_mapped)))
    # Error bound: compare n vs n//2 (rough estimate)
    xi2, wi2 = leggauss(n // 2)
    x2 = 0.5 * (b - a) * xi2 + 0.5 * (b + a)
    r2 = 0.5 * (b - a) * float(np.dot(wi2, np.vectorize(f)(x2)))
    return result, abs(result - r2)

# ── TOE constants ──────────────────────────────────────────────────────────────
ALPHA_INV = 4 * math.pi**3 + math.pi**2 + math.pi   # 137.036303…
ALPHA     = 1 / ALPHA_INV
BREATH_PERIOD = math.pi * ALPHA_INV                  # ≈ 432

# Experimental fine-structure constant (CODATA 2018)
ALPHA_INV_EXP = 137.035999084

PASS_COUNT = 0
FAIL_COUNT = 0
_N = 0


def _mark(n, desc, cond):
    global PASS_COUNT, FAIL_COUNT
    ok = bool(cond)
    PASS_COUNT += ok
    FAIL_COUNT += (not ok)
    print(f"  [{'PASS' if ok else 'FAIL'}] {n:>2}. {desc}")
    return ok


def _next():
    global _N
    _N += 1
    return _N


def check(label: str, value: float, expected: float, tol: float,
          relation: str = "≈") -> bool:
    """Print a labelled PASS/FAIL line and return True on pass."""
    err = abs(value - expected)
    ok  = err <= tol
    _mark(_next(), label, ok)
    print(f"         computed  = {value:.10f}")
    print(f"         expected {relation} {expected:.10f}  (tol={tol:.2e}, err={err:.2e})")
    return ok


def check_not_equal(label: str, a: float, b: float, threshold: float) -> bool:
    """Assert |a - b| > threshold — i.e. the two values are *not* equal."""
    diff = abs(a - b)
    ok   = diff > threshold
    _mark(_next(), label, ok)
    print(f"         |{a:.6f} − {b:.6f}| = {diff:.6f}  (must be > {threshold:.2e})")
    return ok


# ── Density ────────────────────────────────────────────────────────────────────

def rho(x: float) -> float:
    """
    Cubic phase density (P144 eq. 1):
        ρ(x) = 16π³ x³ + 3π² x² + 2π x
    Coefficients motivated by:
        c₃ = 16π³   ← 2·dim(𝕆) = 16,  bulk layer (degree 3)
        c₂ =  3π²   ← dim(adj SU(2)) = 3, boundary layer (degree 2)
        c₁ =  2π    ← |ℤ₂| = 2 or dim(fund SU(2)) = 2, edge layer (degree 1)
    """
    return 16 * math.pi**3 * x**3 + 3 * math.pi**2 * x**2 + 2 * math.pi * x


def rho_times_x3(x: float) -> float:
    """ρ(x) weighted by the natural B⁴ volume measure dV₄ ∝ x³ dx."""
    return rho(x) * x**3


def rho_deg2(x: float) -> float:
    """
    Degree-2 truncation of ρ (no bulk/x³ term):
        ρ₂(x) = 3π² x² + 2π x
    Used to verify the parenthetical in §5 open item 3:
    'Degree 2 integrates to ≈ 13.01'.
    """
    return 3 * math.pi**2 * x**2 + 2 * math.pi * x


def integrand_cp3_stripped(x: float) -> float:
    """
    x³ · (16x³ − 3x)  — coefficient-stripped sub-integrand.
    Isolates the cross-terms between the bulk x³ measure and the
    highest/lowest monomials of ρ without π factors.
    Prompt-specified check.
    """
    return x**3 * (16 * x**3 - 3 * x)


# ── Analytic reference values ──────────────────────────────────────────────────

# ∫₀¹ ρ(x) dx  =  16π³/4 + 3π²/3 + 2π/2  =  4π³ + π² + π  = α⁻¹
ALPHA_INV_ANALYTIC = 4 * math.pi**3 + math.pi**2 + math.pi

# ∫₀¹ ρ(x)·x³ dx  =  16π³/7 + 3π²/6 + 2π/5  =  16π³/7 + π²/2 + 2π/5
MU3_ANALYTIC = (16 * math.pi**3 / 7
                + math.pi**2 / 2
                + 2 * math.pi / 5)

# ∫₀¹ x³(16x³ − 3x) dx  =  16/7 − 3/5  =  59/35
CP3_STRIPPED_ANALYTIC = 16 / 7 - 3 / 5   # = 59/35 ≈ 1.685714...

# ∫₀¹ ρ₂(x) dx  =  3π²/3 + 2π/2  =  π² + π
DEG2_ANALYTIC = math.pi**2 + math.pi


# ══════════════════════════════════════════════════════════════════════════════
print("verify_P144.py — Addendum 144: Uniqueness of α⁻¹")
print("Choice-Point Analysis of the (B⁴, S³) derivation")
print()

# ── Section 1: TOE constants ───────────────────────────────────────────────────
print("S1  Constants")
print(f"  α⁻¹  (TOE formula) = {ALPHA_INV:.10f}")
print(f"  α⁻¹  (experiment)  = {ALPHA_INV_EXP:.10f}")
print(f"  Δ (discrepancy)    = {ALPHA_INV - ALPHA_INV_EXP:.6e}  "
      f"({(ALPHA_INV - ALPHA_INV_EXP) / ALPHA_INV_EXP * 1e6:.3f} ppm)")
print(f"  BREATH_PERIOD      = {BREATH_PERIOD:.6f}")
print()

# ── Section 2: Standard flat-measure integral (P144 eq. 2) ────────────────────
print("S2  Standard flat-measure integral ∫₀¹ ρ(x) dx")
print("   Claim (P144 eq. 2): = 4π³ + π² + π = α⁻¹")
print()

flat_numerical, flat_err = quad(rho, 0, 1)

# Numerical ≈ analytic
check("∫₀¹ ρ(x) dx  numerical ≈ analytic (4π³+π²+π)",
      flat_numerical, ALPHA_INV_ANALYTIC, tol=1e-10)

# Analytic == α⁻¹ by construction (exact algebraic identity)
check("4π³ + π² + π  =  ALPHA_INV (exact identity)",
      ALPHA_INV_ANALYTIC, ALPHA_INV, tol=0.0)

# CP-1: formula is NOT exact — discrepancy is ≈ 2.2 ppm (P144 §1).
# The check verifies the known discrepancy is in the 1–5 ppm range,
# confirming the formula is close but not exact (the core of CP-1).
ppm_diff = abs(ALPHA_INV - ALPHA_INV_EXP) / ALPHA_INV_EXP * 1e6
print(f"  Note: ppm discrepancy = {ppm_diff:.4f} ppm  (P144 §1 states ≈ 2.2 ppm)")
# Verify the discrepancy is nonzero (formula ≠ experiment)
check_not_equal("4π³+π²+π ≠ α⁻¹_exp  (CP-1: formula is not exactly exact)",
                ALPHA_INV, ALPHA_INV_EXP, threshold=1e-4)
# Verify the discrepancy is in the expected 1–5 ppm range
check("ppm discrepancy in expected range 1–5 ppm  (paper says ≈ 2.2 ppm)",
      ppm_diff, 2.2, tol=1.0)
print()

# ── Section 3: CP-3 — natural B⁴ volume measure (P144 §3) ────────────────────
print("S3  CP-3: natural B⁴ volume measure ∫₀¹ ρ(x)·x³ dx")
print("   Claim (P144 §3): ≈ 77.06 ≠ α⁻¹")
print()

mu3_numerical, mu3_err = quad(rho_times_x3, 0, 1)

# Numerical ≈ analytic (16π³/7 + π²/2 + 2π/5)
check("∫₀¹ ρ(x)·x³ dx  numerical ≈ analytic (16π³/7 + π²/2 + 2π/5)",
      mu3_numerical, MU3_ANALYTIC, tol=1e-10)

# ≈ 77.06 (paper's rounded value)
check("∫₀¹ ρ(x)·x³ dx  ≈ 77.06  (paper rounding)",
      mu3_numerical, 77.06, tol=0.01)

# μ₃ ≠ α⁻¹ (the whole point of CP-3)
check_not_equal("μ₃ ≠ α⁻¹  (CP-3: the two measures give different results)",
                mu3_numerical, ALPHA_INV, threshold=50.0)

print()
print(f"  analytic closed form:  16π³/7 + π²/2 + 2π/5")
print(f"    = {16 * math.pi**3:.6f}/7 + {math.pi**2:.6f}/2 + {2 * math.pi:.6f}/5")
print(f"    = {16 * math.pi**3 / 7:.6f} + {math.pi**2 / 2:.6f} + {2 * math.pi / 5:.6f}")
print(f"    = {MU3_ANALYTIC:.10f}")
print()

# ── Section 4: Prompt-specified sub-integrand x³(16x³ − 3x) ─────────────────
print("S4  Sub-integrand  ∫₀¹ x³·(16x³ − 3x) dx")
print("   Coefficient-stripped cross-term (bulk measure vs outer monomials of ρ)")
print()

cp3s_numerical, cp3s_err = quad(integrand_cp3_stripped, 0, 1)

# = 16/7 - 3/5 = 59/35
check("∫₀¹ x³(16x³−3x) dx  numerical ≈ 59/35  (= 16/7 − 3/5)",
      cp3s_numerical, CP3_STRIPPED_ANALYTIC, tol=1e-10)

check("∫₀¹ x³(16x³−3x) dx  numerical ≈ analytic",
      cp3s_numerical, 59 / 35, tol=1e-12)
print()

# ── Section 5: Degree-2 truncation (P144 §5 open item 3) ─────────────────────
print("S5  Degree-2 truncation  ∫₀¹ ρ₂(x) dx")
print("   ρ₂(x) = 3π²x² + 2πx  (boundary + edge only, no bulk term)")
print("   Claim (P144 §5): 'Degree 2 integrates to ≈ 13.01'")
print()

deg2_numerical, deg2_err = quad(rho_deg2, 0, 1)

# = π² + π ≈ 13.01
check("∫₀¹ ρ₂(x) dx  numerical ≈ analytic (π² + π)",
      deg2_numerical, DEG2_ANALYTIC, tol=1e-10)

check("∫₀¹ ρ₂(x) dx  ≈ 13.01  (paper claim)",
      deg2_numerical, 13.01, tol=0.01)

# Much less than α⁻¹ — confirms that degree-3 is needed
check_not_equal("ρ₂ integral ≠ α⁻¹  (degree-2 is insufficient)",
                deg2_numerical, ALPHA_INV, threshold=100.0)
print()

# ── Section 6: Conditional uniqueness theorem (P144 Theorem 1) ───────────────
print("S6  Conditional uniqueness (P144 Theorem 1)")
print("   Under (A1) polynomial basis, (A2) flat dx, (A3) α⁻¹ exact, (A4) grading:")
print("   c₃ = 16π³, c₂ = 3π², c₁ = 2π are uniquely determined.")
print()

# Verify the back-solve: given α⁻¹, the coefficients are forced
# ∫₀¹ c₃x³ dx = c₃/4 = 4π³  →  c₃ = 16π³
# ∫₀¹ c₂x² dx = c₂/3 = π²   →  c₂ = 3π²
# ∫₀¹ c₁x  dx = c₁/2 = π    →  c₁ = 2π
c3_recovered = 4 * (4 * math.pi**3)     # = 16π³
c2_recovered = 3 * (math.pi**2)         # = 3π²
c1_recovered = 2 * (math.pi)            # = 2π

check("c₃ recovered = 16π³", c3_recovered, 16 * math.pi**3, tol=1e-10)
check("c₂ recovered = 3π²",  c2_recovered,  3 * math.pi**2, tol=1e-10)
check("c₁ recovered = 2π",   c1_recovered,  2 * math.pi,    tol=1e-10)

# Integer factors
k3 = round(c3_recovered / math.pi**3)
k2 = round(c2_recovered / math.pi**2)
k1 = round(c1_recovered / math.pi)
print()
print(f"  Integer factors (k₃, k₂, k₁) = ({k3}, {k2}, {k1})")
print(f"    k₃ = 16 = 2·dim(𝕆)           ✓" if k3 == 16 else f"    k₃ = {k3}  ✗")
print(f"    k₂ =  3 = dim(adj SU(2))      ✓" if k2 ==  3 else f"    k₂ = {k2}  ✗")
print(f"    k₁ =  2 = |ℤ₂|               ✓" if k1 ==  2 else f"    k₁ = {k1}  ✗")
print()

# ── Section 7: J₃(𝕆) Peirce decomposition integer pattern ───────────────────
print("S7  J₃(𝕆) Peirce decomposition integer pattern")
print("   Claim: (16, 3, 2) read off from Peirce without circularity")
print()

# Peirce: 3 diagonal idempotents + 3 off-diagonal sectors V_ij ≅ 𝕆
dim_O         = 8           # dim(𝕆) as ℝ-algebra
n_diag        = 3           # diagonal idempotents e₁, e₂, e₃
n_offdiag     = 3           # off-diagonal pairs (1,2),(1,3),(2,3)
dim_peirce    = n_diag + n_offdiag * dim_O   # = 3 + 24 = 27

# k₃: each diagonal eᵢ is adjacent to two V_ij sectors of total dim 2·8=16
k3_peirce = 2 * dim_O          # 16

# k₂: dim(diagonal subspace) = 3
k2_peirce = n_diag             # 3

# k₁: each V_ij carries ℤ₂ grading from Cayley–Dickson ℍ→𝕆
k1_peirce = 2                  # |ℤ₂|

peirce_ok = (k3_peirce == 16 and k2_peirce == 3 and k1_peirce == 2
             and dim_peirce == 27)

if peirce_ok:
    _mark(_next(), f"J₃(𝕆) dim = {dim_peirce}  (= 3 + 3·8 = 27)  ✓", True)
    print(f"         Peirce factors (k₃,k₂,k₁) = ({k3_peirce},{k2_peirce},{k1_peirce})"
          f" match TOE coefficients  ✓")
else:
    _mark(_next(), "J₃(𝕆) Peirce factors do not match", False)
print()

# ── Summary ────────────────────────────────────────────────────────────────────
print()
print("  Key numerical results:")
print(f"    α⁻¹  (flat dx measure)       = {flat_numerical:.10f}")
print(f"    μ₃   (x³ dx measure)         = {mu3_numerical:.10f}   ← CP-3")
print(f"    Δ(μ₃, α⁻¹)                   = {abs(mu3_numerical - ALPHA_INV):.6f}")
print(f"    ∫ x³(16x³−3x) dx             = {cp3s_numerical:.10f}   (= 59/35)")
print(f"    deg-2 integral (π²+π)        = {deg2_numerical:.10f}")
print()
print("  Choice-point summary (P144):")
print("    CP-1  Exactness: 4π³+π²+π ≠ α⁻¹_exp  (Δ = 3.05e-4 / 0.22 ppm)")
print("    CP-2  Functional form: polynomial basis not forced by S³ geometry")
print(f"    CP-3  Measure: flat dx → {flat_numerical:.4f},  x³dx → {mu3_numerical:.4f}  (gap = {abs(flat_numerical-mu3_numerical):.4f})")
print("    CP-4  Edge coefficient: two distinct justifications (dim vs |ℤ₂|)")
print("    G1 remains open until CP-1 and CP-3 are resolved.")

print(f"\n{'='*60}\nRESULT: {PASS_COUNT} PASS / {FAIL_COUNT} FAIL")
sys.exit(0 if FAIL_COUNT == 0 else 1)
