#!/usr/bin/env python3
"""
verify_P055.py -- Addendum 55: Seesaw scale from the E6 adjoint sector.

This verifier checks the numerical five-option survey in
55_Addendum_SeesawScale.tex.  Most of the Option A/B/D/E energy arithmetic is
reproducible.  The flagged items are internal consistency/status problems:
the paper mixes incompatible Planck-coordinate definitions, the Option C RG
formula has the wrong displayed sign and stale b0=9/11 table values, two
Option B mass-table rows do not follow from their listed energies, and the
"unique within 5%" / "within 20%" / exact-yukawa-proof claims overstate what
the paper itself establishes.
"""

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 output adapter: inherits Verifier's tolerance logic unchanged,
    emits the corpus's modern check-line format (numbered [PASS]/[FAIL]
    lines, computed/claimed as indented info lines)."""

    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 = label if (ok or not detail) else f"{label} -- {detail}"
        print(f"  [{'PASS' if ok else 'FAIL'}] {n:>2}. {desc}")
        if computed != "" or claimed != "":
            print(f"        computed: {computed}")
            print(f"        claimed : {claimed}")
        if ok and detail:
            print(f"        {detail}")
        return ok

    def summary(self):
        passed = sum(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("P055 -- Seesaw Scale from E6 Adjoint")

ROOT = Path(__file__).resolve().parents[1]
TEX = (ROOT / "55_Addendum_SeesawScale.tex").read_text()

PI = math.pi
MU0 = 4 * PI**3 + PI**2 + PI
MU1 = 16 * PI**3 / 5 + 3 * PI**2 / 4 + 2 * PI / 3
MU = MU1 / MU0
ME_GEV = 0.511e-3
V_EW = 246.22
DM31 = 2.45e-3
MNU3_GEV = math.sqrt(DM31) * 1e-9
MR_TARGET = 1.24e15
ER_TARGET = PI + math.log(MR_TARGET / ME_GEV) / MU
MR_E = V_EW**2 / MNU3_GEV
ER_E = PI + math.log(MR_E / ME_GEV) / MU


def mass_from_energy(energy: float) -> float:
    return ME_GEV * math.exp(MU * (energy - PI))


def energy_from_mass(mass_gev: float) -> float:
    return PI + math.log(mass_gev / ME_GEV) / MU


def pct_energy(energy: float) -> float:
    return 100 * (energy - 56.502) / 56.502


v.check("mu0", MU0, 137.0363, rel=5e-7)
v.check("mu1", MU1, 108.7167, rel=5e-7)
v.check("MU", MU, 0.79334, rel=5e-6)
v.check("E_bulk", 4 * PI**3, 124.025, rel=1e-5)

mpl_table = ME_GEV * math.exp(MU * MU1 / PI)
e_mpl_from_mpl_table = energy_from_mass(mpl_table)
v.check("TOE Planck mass table value", mpl_table, 4.28e8, rel=5e-3)
v.check(
    "printed E_Pl = pi + mu1/MU",
    PI + MU1 / MU,
    137.3,
    rel=5e-3,
    detail="Expected fail: the displayed formula equals pi+mu0≈140.178, not 137.3.",
)
v.record(
    "TOE Planck mass and E_Pl coordinate are mutually consistent",
    abs(e_mpl_from_mpl_table - (PI + MU1 / MU)) < 1e-6,
    computed=f"M_Pl table corresponds to E={e_mpl_from_mpl_table:.3f}",
    claimed=f"E_Pl=pi+mu1/MU≈{PI + MU1 / MU:.3f}",
    detail="Expected fail: the mass table uses exponent MU*mu1/pi, which corresponds to E=pi+mu1/pi, not pi+mu1/MU.",
)

v.check("target M_R from rounded paper value", MR_TARGET, 1.24e15, rel=1e-12)
v.check("target E_R from M_R=1.24e15", ER_TARGET, 56.502, rel=5e-6)
v.check("Option E m_nu3", MNU3_GEV / 1e-9, 4.950e-2, rel=7e-5)
v.check("Option E M_R", MR_E, 1.225e15, rel=5e-4)
v.check("Option E E_R", ER_E, 56.486, rel=1e-5)
v.check("Option E energy error percent", 100 * (ER_E - ER_TARGET) / ER_TARGET, -0.028, rel=3e-2)
v.check("Option E mass residual vs rounded target", 100 * (MR_E - MR_TARGET) / MR_TARGET, -1.3, rel=7e-2)

for exponent, claimed_m, claimed_e, claimed_err in [
    (1 / 3, 2.0e8, 36.79, -34.9),
    (1 / 2, 1.4e8, 36.31, -35.7),
    (2 / 3, 9.4e7, 35.83, -36.6),
    (1.0, 4.4e7, 34.88, -38.3),
    (2.0, 4.5e6, 32.01, -43.4),
]:
    mass = mpl_table * (8 / 78) ** exponent
    energy = energy_from_mass(mass)
    suffix = f"n={exponent:g}"
    v.check(f"Option A mass {suffix}", mass, claimed_m, rel=5e-2)
    v.check(f"Option A energy {suffix}", energy, claimed_e, rel=5e-4)
    v.check(f"Option A error {suffix}", pct_energy(energy), claimed_err, rel=5e-3)

option_b = [
    ("mu1/2", MU1 / 2, 54.358, -3.8, 2.26e14),
    ("mu1/2 + pi MU", MU1 / 2 + PI * MU, 56.851, 0.6, 1.64e15),
    ("pi(1+pi)^2", PI * (1 + PI) ** 2, 53.887, -4.6, 1.56e14),
    ("2pi^3 MU", 2 * PI**3 * MU, 49.197, -12.9, 6.6e12),
    ("pi^4/2", PI**4 / 2, 48.705, -13.8, 3.9e12),
]
for name, energy, claimed_e, claimed_err, claimed_mass in option_b:
    mass = mass_from_energy(energy)
    v.check(f"Option B energy {name}", energy, claimed_e, rel=5e-5)
    v.check(f"Option B error {name}", pct_energy(energy), claimed_err, rel=3e-2)
    expected_fail = name in {"2pi^3 MU", "pi^4/2"}
    v.check(
        f"Option B mass {name}",
        mass,
        claimed_mass,
        rel=5e-2,
        detail="Expected fail: this physical-mass row does not follow from the listed energy."
        if expected_fail
        else "",
    )

alpha_planck = 0.039
v.record(
    "Option C displayed RG sign can produce sub-Planck confinement scales",
    False,
    computed="with the printed minus sign and M_R<M_Pl, 1/alpha_R increases instead of falling to 1",
    claimed="standard running gives QCD-like GeV scales",
    detail="Expected fail: the listed low scales require the opposite sign convention in the displayed equation.",
)
for b0, claimed_mass in [(7, 0.11), (9, 0.49), (11, 1.27)]:
    mass = mpl_table * math.exp((1 - 1 / alpha_planck) * 2 * PI / b0)
    v.check(
        f"Option C corrected-sign mass b0={b0}",
        mass,
        claimed_mass,
        rel=6e-2,
        detail="Expected fail for b0=9/11: the table values are stale under the stated alpha_s(M_Pl)=0.039."
        if b0 in {9, 11}
        else "",
    )

e_d = 4 * PI**3 / 4
m_d = mass_from_energy(e_d)
v.check("Option D Killing-form energy", e_d, 31.01, rel=2e-4)
v.check("Option D Killing-form mass", m_d, 2.0e6, rel=2e-2)
v.check("Option D energy error", pct_energy(e_d), -45.0, rel=3e-3)

e_v = energy_from_mass(V_EW)
e_nu = energy_from_mass(MNU3_GEV)
v.check("electroweak VEV energy", e_v, 19.636, rel=3e-5)
v.check("light neutrino energy from sqrt(Delta m31)", e_nu, -17.23, rel=1e-3)
v.check("seesaw energy reflection exact", 2 * e_v - e_nu, ER_E, rel=1e-12)
v.check("target-route positive neutrino gap", ER_TARGET - 2 * e_v, 17.231, rel=5e-5)

within_five = [
    ("mu1/2", abs(pct_energy(MU1 / 2))),
    ("mu1/2 + pi MU", abs(pct_energy(MU1 / 2 + PI * MU))),
    ("Option E", abs(100 * (ER_E - ER_TARGET) / ER_TARGET)),
]
v.record(
    "Option E is the unique candidate within 5 percent",
    sum(gap < 5 for _, gap in within_five) == 1,
    computed=", ".join(f"{name}: {gap:.3f}%" for name, gap in within_five),
    claimed="Option E unique within 5%",
    detail="Expected fail: both Option B near-misses are also within 5% in the energy coordinate.",
)
v.record(
    "Option B mass near-miss is within a 20 percent threshold after Delta m31 uncertainty",
    abs(mass_from_energy(MU1 / 2 + PI * MU) / MR_TARGET - 1) < 0.2,
    computed=f"relative mass gap={100 * (mass_from_energy(MU1 / 2 + PI * MU) / MR_TARGET - 1):.2f}%",
    claimed="within 20% after accounting for known Delta m31 uncertainty",
    detail="Expected fail: the mass gap is about 32%, far larger than the stated neutrino-splitting uncertainty.",
)
v.record(
    "y_nu=1 is proved as an exact E6 group-theory result in P55",
    "Structural argument, not proved" not in TEX,
    computed="open-problem table says: Structural argument, not proved",
    claimed="exact prediction of the group theory",
    detail="Expected status fail: P55 itself classifies the unit-Yukawa statement as not fully proved.",
)
v.record(
    "Option E is presented as a consistency check rather than a first-principles prediction",
    "not a prediction from first principles" in TEX
    and "phenomenological input" in TEX,
    computed="explicit caveat present",
    claimed="consistency-check status",
)

sys.exit(v.summary())
