#!/usr/bin/env python3
"""
verify_P013.py -- Paper 13: quintic structure.

Checks inherited density/moment/self-energy arithmetic and flags the missing
quintic data needed to verify the central theorem.
"""

from __future__ import annotations

import math
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
class Verifier:
    """Output shim: identical tolerance semantics to verify_common.Verifier,
    modern [PASS]/[FAIL] check-line output format."""

    def __init__(self, name):
        self.PASS = 0
        self.FAIL = 0
        self.n = 0
        print(name)

    def _mark(self, ok, desc):
        self.n += 1
        if ok:
            self.PASS += 1
        else:
            self.FAIL += 1
        print(f"  [{'PASS' if ok else 'FAIL'}] {self.n:>2}. {desc}")

    def check(self, label, computed, claimed, *, rel=1e-3, abs_tol=None, detail=""):
        if abs_tol is not None:
            ok = abs(computed - claimed) <= abs_tol
            err_detail = f"abs err={abs(computed - claimed):.6g}, tol={abs_tol:.6g}"
        else:
            if claimed == 0:
                ok = abs(computed) <= (rel or 1e-12)
                err_detail = f"abs value={abs(computed):.6g}, tol={rel:.6g}"
            else:
                err = (computed - claimed) / abs(claimed)
                ok = abs(err) <= (rel or 0)
                err_detail = f"rel err={100 * err:+.6g}%, tol={100 * (rel or 0):.6g}%"
        self._mark(ok, label + (f" -- {detail}" if detail else ""))
        print(f"        computed: {computed}   claimed: {claimed}   ({err_detail})")
        return ok

    def record(self, label, ok, computed="", claimed="", detail=""):
        ok = bool(ok)
        self._mark(ok, label + (f" -- {detail}" if detail else ""))
        if computed != "" or claimed != "":
            print(f"        computed: {computed}   claimed: {claimed}")
        return ok

    def summary(self):
        print(f"\n{'='*60}\nRESULT: {self.PASS} PASS / {self.FAIL} FAIL")
        return 0 if self.FAIL == 0 else 1


v = Verifier("P013 -- Quintic Structure")

ROOT = Path(__file__).resolve().parents[2]
TEX = (ROOT / "toe" / "13_Paper_QuinticStructure.tex").read_text()

PI = math.pi


def mu(n: int) -> float:
    return 16.0 * PI**3 / (n + 4) + 3.0 * PI**2 / (n + 3) + 2.0 * PI / (n + 2)


def rho_prime_square_integral() -> float:
    # rho'(x)=48*pi^3*x^2 + 6*pi^2*x + 2*pi.
    a = 48.0 * PI**3
    b = 6.0 * PI**2
    c = 2.0 * PI
    return a * a / 5.0 + 2.0 * a * b / 4.0 + (b * b + 2.0 * a * c) / 3.0 + 2.0 * b * c / 2.0 + c * c


mu0 = mu(0)
mu1 = mu(1)
mu2 = mu(2)
alpha = 1.0 / mu0
e_self = rho_prime_square_integral() / (2.0 * mu0 * mu0)
kappa = alpha ** (5.0 / 4.0)

v.record("TeX source is present", "Quintic Structure" in TEX)
v.check("mu0 density moment", mu0, 4.0 * PI**3 + PI**2 + PI, rel=1e-15)
v.check("mu1 density moment", mu1, 108.71668, rel=5e-8)
v.check("mu2 density moment", mu2, 90.17596, rel=5e-8)
v.check("self-lensing energy", e_self, 13.177, rel=3e-5)
v.check("alpha from mu0 inverse", alpha, 1.0 / (4.0 * PI**3 + PI**2 + PI), rel=1e-15)
v.check("kappa alpha^(5/4)", kappa, 0.002133, rel=2e-4)
v.check("moment ratio beta", mu1 / mu0, 0.793342, rel=3e-7)
v.record(
    "raising kappa law removes fractional exponent",
    True,
    computed="(alpha^(5/4))^4 = alpha^5 for alpha>0",
    claimed="kappa_geom(alpha)^4 = alpha^5",
)

v.record(
    "quintic polynomial coefficients are supplied",
    False,
    computed="the paper gives placeholders a5...a0 and N(alpha),D(alpha), but no explicit coefficients",
    claimed="P(alpha)=a5 alpha^5+...+a0 is the quintic",
    detail="Expected reproducibility fail.",
)
v.record(
    "elimination generically yields degree five",
    False,
    computed="if kappa_geom=N/D with nonconstant polynomials, N^4-alpha^5 D^4 generally has degree max(4 deg N, 5+4 deg D), not necessarily 5",
    claimed="clearing denominators yields a quintic",
    detail="Expected algebra-scope fail.",
)
v.record(
    "lambda1(alpha) depends rationally on alpha",
    False,
    computed="lambda1 is an eigenvalue of a differential operator; no formula is supplied showing rational dependence on alpha",
    claimed="both lambda1 and beta depend on alpha rationally",
    detail="Expected spectral-dependence fail.",
)
v.record(
    "electron mass constraint F is defined",
    False,
    computed="F(lambda1(alpha), beta(alpha))=0 is named but not specified, and no electron-mass normalization equation is printed",
    claimed="Condition 2 eigenvalue constraint",
    detail="Expected missing-definition fail.",
)
v.record(
    "irreducibility is proved",
    False,
    computed="without explicit integer/rational coefficients, rational-root testing and irreducibility checks cannot be performed",
    claimed="no rational root exists and the quintic is irreducible",
    detail="Expected proof-data fail.",
)
v.record(
    "Galois group S5 is established",
    False,
    computed="no polynomial, discriminant, resolvent, modular factorization, or other Galois-group computation is supplied",
    claimed="Galois group is S5",
    detail="Expected proof-data fail.",
)
v.record(
    "unique positive root equals physical alpha",
    False,
    computed="no explicit P(alpha), root isolation, sign analysis, or Newton trace is included",
    claimed="unique positive real root is the physical alpha",
    detail="Expected verification fail.",
)
v.record(
    "all numerical verification methods are shown",
    False,
    computed="the program is described, but no coefficient file, Newton iteration, root table, or eigenvalue computation is present",
    claimed="all methods converge to the same value",
    detail="Expected reproducibility fail.",
)
v.record(
    "paper completes the structural link",
    False,
    computed="the central quintic and spectral inverse problem are placeholders, so the claimed closure is not established in this TeX",
    claimed="completes the missing structural link/theoretical circle",
    detail="Expected status overstatement.",
)

sys.exit(v.summary())
