#!/usr/bin/env python3
"""
verify_P064.py -- Addendum 64: E6 seesaw-scale structure.

This verifier checks the P64 spectral-reflection, Killing-form, and Option-B
near-miss arithmetic.  The constants, embedding-index arithmetic, Option-B
energy, and V_R norm estimates mostly reproduce.  The flagged issues are
internal consistency problems: the abstract's kappa=12/78 conflicts with the
body's corrected Casimir ratio 1; the Killing-form table uses E_bulk^n even
though the displayed formula with ratio=1 gives E_bulk for every n; and the
neutrino numerical check mixes an incorrect meV-to-GeV conversion with the
target-route E_nu value.
"""

from __future__ import annotations

import math
import sys
from pathlib import Path

PASS = FAIL = 0
_N = 0


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


class Verifier:
    """Same check semantics as verify_common.Verifier; modern output style."""

    def __init__(self, name):
        print(name)

    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 = abs(computed - claimed)
            err_detail = f"abs err={err:.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}%"
        return self.record(label, ok, computed, claimed, err_detail + (f"; {detail}" if detail else ""))

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

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


v = Verifier("P064 -- E6 Seesaw-Scale Derivation")

ROOT = Path(__file__).resolve().parents[1]
TEX = (ROOT / "64_Addendum_SeesawScaleDerivation.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
MNU_GEV = 49.5e-3 * 1e-9
MR_TARGET = 1.24e15
E_BULK = 4 * PI**3


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


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


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


v.check("mu0", MU0, 137.036, rel=3e-6)
v.check("mu1", MU1, 108.717, rel=5e-6)
v.check("MU", MU, 0.79334, rel=5e-6)
v.check("E_v from 246.22 GeV", energy(V_EW), 19.636, rel=3e-5)
v.check(
    "E_nu3 from 49.5 meV",
    energy(MNU_GEV),
    -17.231,
    rel=5e-4,
    detail="Expected fail: 49.5 meV gives E_nu≈-17.215, while -17.231 is the rounded target-route value.",
)
v.check("E_R from 1.24e15 GeV", energy(MR_TARGET), 56.502, rel=5e-6)

v.check("adjoint dimension branch sum", 8 + 8 + 8 + 27 + 27, 78, rel=0)
v.check("embedding index 12/3", 12 / 3, 4, rel=0)
v.check("E6 restricted Killing form H1", 4 * 2 * 3, 24, rel=0)
v.check("E6 Casimir on (1,1,8)", 4 * 3, 12, rel=0)
v.check("Casimir over hvee(E6)", (4 * 3) / 12, 1, rel=0)
v.record(
    "abstract kappa=12/78 agrees with body Casimir ratio",
    abs(12 / 78 - 1) < 1e-12,
    computed=f"12/78={12/78:.6f}, body ratio={(4*3)/12:.1f}",
    claimed="same Cartan/Casimir eigenvalue",
    detail="Expected consistency fail: the abstract says kappa=12/78, while the body derives ratio 1.",
)

for n, claimed in [(1, 124.025), (0.5, 11.14), (-1, 0.00806)]:
    formula_value = E_BULK * (1**n)
    v.check(
        f"Killing table from displayed formula n={n:g}",
        formula_value,
        claimed,
        rel=2e-3,
        detail="Expected fail for n=1/2 and n=-1: with ratio=1, E_bulk*(ratio)^n remains E_bulk."
        if n != 1
        else "",
    )
v.record(
    "text conclusion E_R^(K)=E_bulk^n follows from ratio=1",
    False,
    computed="E_bulk*(1)^n = E_bulk for all n",
    claimed="E_R^(K)=E_bulk^n",
    detail="Expected algebra fail: the table switches from raising the ratio to raising E_bulk itself.",
)

ev = energy(V_EW)
enu = energy(MNU_GEV)
er_from_reflection = 2 * ev - enu
er_target = energy(MR_TARGET)
v.check(
    "spectral reflection using stated v and 49.5 meV",
    er_from_reflection,
    56.503,
    rel=5e-5,
    detail="Expected fail: using 49.5 meV gives about 56.486, not 56.503.",
)
v.check(
    "reflection residual vs target percent",
    pct(er_from_reflection, er_target),
    0.002,
    rel=5e-1,
    detail="Expected fail: exact stated masses give about -0.028%, not +0.002%.",
)
v.record(
    "meV-to-GeV conversion in E_nu numerical check is correct",
    False,
    computed="49.5 meV = 4.95e-11 GeV, not 49.5e-3*1e-6 GeV",
    claimed="49.5e-3*1e-6 GeV and ratio 9.687e-5",
    detail="Expected unit fail: the displayed intermediate conversion is off by 10^3 and conflicts with the final E_nu value.",
)

option_b = MU1 / 2 + PI * MU
v.check("Option B mu1/2", MU1 / 2, 54.359, rel=2e-5)
v.check("Option B pi*MU", PI * MU, 2.491, rel=7e-4)
v.check("Option B energy", option_b, 56.850, rel=2e-5)
v.check("Option B residual vs 56.502", pct(option_b, 56.502), 0.616, rel=3e-3)
v.check("Option B factor", 0.5 + PI / MU0, 0.5229, rel=5e-5)
mr_b = mass_from_energy(option_b)
v.check("Option B M_R", mr_b, 1.64e15, rel=5e-3)
mnu_b_mev = V_EW**2 / mr_b * 1e12
v.check("Option B implied m_nu3", mnu_b_mev, 37.0, rel=3e-3)
v.check("Option B mass-space miss", pct(mnu_b_mev, 49.5), -25, rel=2e-2)

e_vr = PI + math.log(2) / MU
v.check("V_R norm squared", 4 * ((1 + 1 + 4) / 6), 4, rel=0)
v.check("V_R norm energy", e_vr, 4.01, rel=2e-3)
v.check("V_R norm mass", mass_from_energy(e_vr) * 1000, 1.01, rel=2e-2)
v.record(
    "unit-Yukawa statement is marked as structural not formal",
    "structural argument, not a formal proof" in TEX,
    computed="formal-proof caveat present",
    claimed="status acknowledged",
)

sys.exit(v.summary())
