#!/usr/bin/env python3
"""
verify_P017.py -- Paper 17: gravity as a geometric droplet.

This verifier checks the explicit moment arithmetic, the Planck/electron
logarithm formula, coefficient decomposition, self-lensing factor, KK-scale
comparison, and appendix/bulk-spectrum consistency in
toe/17_Paper_GravityDroplet.tex.

The headline numeric formula reproduces at the paper's rounded precision. The
flagged issues are derivational/internal: the pi/7 shortcut is arithmetically
wrong, the body and appendix quote incompatible spectra, the Dirac numerical
problem is not reproducible from the TeX alone, and several "verified" physical
claims are asserted or inherited rather than proved in this paper.
"""

from __future__ import annotations

import math
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
from verify_common import CheckResult, Verifier


class _ModernVerifier(Verifier):
    """Local adapter: identical tolerance logic, modern output format."""

    def __init__(self, name: str):
        self.name = name
        self.results = []
        print(name)

    def record(self, label, ok, computed="", claimed="", detail=""):
        self.results.append(CheckResult(label, ok, computed, claimed, detail))
        n = len(self.results)
        desc, info = label, detail
        i = detail.find("Expected")
        if i >= 0:
            desc = f"{label} -- {detail[i:]}"
            info = detail[:i].rstrip().rstrip(";")
        print(f"  [{'PASS' if ok else 'FAIL'}] {n:>2}. {desc}")
        if computed != "" or claimed != "":
            print(f"        computed: {computed}")
            print(f"        claimed : {claimed}")
        if info:
            print(f"        {info}")
        return bool(ok)

    def summary(self) -> int:
        passed = sum(bool(r.ok) for r in self.results)
        failed = len(self.results) - passed
        print(f"\n{'='*60}\nRESULT: {passed} PASS / {failed} FAIL")
        return 1 if failed else 0


v = _ModernVerifier("P017 -- Gravity Droplet / Planck Log")

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

PI = math.pi
MU0 = 4.0 * PI**3 + PI**2 + PI
MU1 = 16.0 * PI**3 / 5.0 + 3.0 * PI**2 / 4.0 + 2.0 * PI / 3.0
MU2 = 16.0 * PI**3 / 6.0 + 3.0 * PI**2 / 5.0 + 2.0 * PI / 4.0
MU3 = 16.0 * PI**3 / 7.0 + 3.0 * PI**2 / 6.0 + 2.0 * PI / 5.0
ALPHA = 1.0 / MU0
SELF_LENSING = MU1 * ALPHA**2
PLANCK_LOG = (3.0 * PI / 20.0) * MU1 / (1.0 - SELF_LENSING)
OBS_LOG_ROUNDED = math.log(1.22e19 / (5.11e-4))
OBS_LOG_CODATA_LIKE = math.log(1.22089e19 / 0.00051099895)


def pct(value: float, target: float) -> float:
    return 100.0 * (value - target) / abs(target)


v.check("mu0 alpha inverse", MU0, 137.036304, rel=2e-9)
v.check("mu1 first moment", MU1, 108.716684, rel=3e-9)
v.check("mu2 second moment", MU2, 90.175963, rel=6e-9)
v.check("mu3 third moment", MU3, 77.062929, rel=5e-9)
v.check("mu1/mu0", MU1 / MU0, 0.7933, rel=6e-5)
v.check("mu2/mu1", MU2 / MU1, 0.8295, rel=6e-5)
v.check("mu3/mu2", MU3 / MU2, 0.8546, rel=6e-5)

v.check("alpha squared", ALPHA**2, 5.325e-5, rel=3e-5)
v.check("mu1 alpha^2", SELF_LENSING, 0.005790, rel=2e-4)
v.check("self-lensing denominator", 1.0 - SELF_LENSING, 0.994210, rel=8e-7)
v.check("self-lensing resummation factor", 1.0 / (1.0 - SELF_LENSING), 1.00582, rel=3e-6)
v.check("mu1 over self-lensing denominator", MU1 / (1.0 - SELF_LENSING), 109.349, rel=7e-6)
v.check("3pi/20 coefficient", 3.0 * PI / 20.0, 0.471239, rel=3e-7)
v.check("coefficient dimension decomposition", 3.0 * PI / (4.0 * 5.0), 3.0 * PI / 20.0, rel=1e-12)
v.check("Planck log formula RHS", PLANCK_LOG, 51.5299, rel=1e-6)
v.check("observed log with paper rounded masses", OBS_LOG_ROUNDED, 51.5271, rel=2e-7)
v.check("Planck log percent agreement using rounded masses", abs(pct(PLANCK_LOG, OBS_LOG_ROUNDED)), 0.0054, rel=2e-2)
v.check("observed log with CODATA-like masses", OBS_LOG_CODATA_LIKE, 51.5278, rel=8e-7)
v.check("Planck log percent agreement using CODATA-like masses", abs(pct(PLANCK_LOG, OBS_LOG_CODATA_LIKE)), 0.0039, rel=3e-2)

kk_scale = 1.0 / (8.0 * PI) ** (1.0 / 3.0)
v.check("KK scale 1/(8pi)^(1/3)", kk_scale, 0.34, rel=5e-3)
v.check("m1 to KK-scale ratio", 0.89 / kk_scale, 2.6, rel=5e-3)
v.check("breathing cycle pi alpha^-1", PI * MU0, 430.5, rel=3e-5)
v.check("kappa alpha^(5/4) oscillation scale", ALPHA**1.25, 0.002, rel=8e-2)
v.check("5/4 exponent dimensional decomposition", 1.0 + 3.0 / (4.0 * 3.0), 1.25, rel=1e-12)

v.check(
    "pi/7 times mu1 shortcut",
    PI * MU1 / 7.0,
    51.5,
    rel=1e-2,
    detail="Expected fail: the displayed approximation is about 48.79, not 51.5.",
)
v.record(
    "bulk spectrum in body and appendix are mutually consistent",
    False,
    computed="body: m1~0.89, m2~0.96, m3~1.00; appendix: m1=0.891, m2=6.923, m3=7.763",
    claimed="one discrete spectrum from the same radial problem",
    detail="Expected internal-consistency fail.",
)
v.record(
    "Dirac spectrum is reproducible from the TeX alone",
    False,
    computed="the radial ODE is stated, but lambda/potential normalization, numerical method, mesh, shooting condition, and boundary projection implementation are not specified enough to reproduce the eigenvalues",
    claimed="computational verification by numerical solution",
    detail="Expected solver-reproducibility fail.",
)
v.record(
    "Planck formula is derived from the solved Dirac eigenvalue problem",
    False,
    computed="the fitted log formula uses mu1 and 3pi/20, while the quoted eigenvalues are not used to derive the Planck/electron logarithm",
    claimed="G emerges from the Dirac operator on B4",
    detail="Expected proof-status fail.",
)
v.record(
    "3pi/20 is derived from first principles rather than decomposed",
    False,
    computed="the paper's open-problems section says an exact derivation from the Dirac index theorem is still desirable",
    claimed="fully determined / exact derivation complete",
    detail="Expected proof-status fail: the dimension identity is correct, but the derivation is explicitly still open.",
)
v.record(
    "three-family and strong-CP entries are verified within P17",
    False,
    computed="P17 lists these as verified predictions, but gives no independent proof beyond inherited Z3/symmetry claims already flagged by earlier verifiers",
    claimed="three families exact and strong CP solved",
    detail="Expected proof-status fail.",
)
v.record(
    "zero-free-parameter gravity closure is established",
    False,
    computed="the headline arithmetic is zero-input once the formula is accepted, but the coefficient derivation, self-lensing factor, and Dirac-spectrum bridge remain asserted or open",
    claimed="G derived from first principles with zero free parameters",
    detail="Expected proof-status fail.",
)

sys.exit(v.summary())
