#!/usr/bin/env python3
"""
verify_P090.py -- Addendum 90: Strong Coupling alpha_s.

This verifier checks the numerical claims that follow directly from the
paper's own definitions:

  E(m) = pi + ln(m/m_e)/MU,  m_e = 0.511 MeV
  sin^2(theta_W) = (1 - 4 sin^2(pi/14)/5)/(1 + pi)
  alpha_2(M_Z) = alpha_EM(M_Z)/sin^2(theta_W)

It flags several internal arithmetic inconsistencies:
  * alpha_2^{-1}(M_Z) is about 29.66, not the abstract's 33.05.
  * E_c and E_b printed in the threshold table do not follow E(m).
  * The quoted E6 GUT mass scale is too high by a factor of about 7-8.
"""

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: tolerance logic byte-identical to
    verify_common.Verifier.check; emits the modern corpus line format
    ("  [PASS] {n:>2}. {desc}") with computed/claimed/tolerance values
    kept as indented info lines, and the modern RESULT footer."""

    def __init__(self, name: str):
        self.name = name
        self.results = []
        self._n = 0
        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._emit(label, ok, computed, claimed, err_detail, detail)

    def record(self, label, ok, computed="", claimed="", detail=""):
        return self._emit(label, ok, computed, claimed, "", detail)

    def _emit(self, label, ok, computed, claimed, info, ann):
        full_detail = (info + (f"; {ann}" if ann else "")) if info else ann
        self.results.append(CheckResult(label, ok, computed, claimed, full_detail))
        self._n += 1
        desc = f"{label} -- {ann}" if ann else label
        print(f"  [{'PASS' if ok else 'FAIL'}] {self._n:>2}. {desc}")
        if computed != "" or claimed != "":
            print(f"        computed: {computed}")
            print(f"        claimed : {claimed}")
        if info:
            print(f"        {info}")
        return ok

    def summary(self):
        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("P090 -- Strong Coupling alpha_s")

PI = math.pi
M_E = 0.511
MU0 = 4 * PI**3 + PI**2 + PI
MU1 = 16 * PI**3 / 5 + 3 * PI**2 / 4 + 2 * PI / 3
MU = MU1 / MU0
LAM = math.sin(PI / 14)
SIN2_W = (1 - 4 * LAM**2 / 5) / (1 + PI)
ALPHA_EM_MZ = 1 / 127.9
ALPHA2 = ALPHA_EM_MZ / SIN2_W
ALPHA2_INV = 1 / ALPHA2
ALPHA_S_MZ = 0.1179
ALPHA_S_INV_MZ = 1 / ALPHA_S_MZ


def spectral_e(m_mev):
    return PI + math.log(m_mev / M_E) / MU


v.check("mu0 = 4*pi^3 + pi^2 + pi", MU0, 137.036, rel=3e-6)
v.check("MU = mu1/mu0", MU, 0.79334, rel=5e-6)
v.check("lambda = sin(pi/14)", LAM, 0.22252, rel=5e-6)
v.check("lambda^2", LAM**2, 0.049516, rel=2e-5)
v.check("sin^2 theta_W NLO", SIN2_W, 0.23192, rel=2e-4)
v.check("SU(5) Weinberg angle 3/8", 3 / 8, 0.375, rel=1e-12)
v.check("sin^2 theta_W / (3/8)", SIN2_W / (3 / 8), 0.61845, rel=2e-3)

v.check("alpha_EM(MZ) = 1/127.9", ALPHA_EM_MZ, 7.818e-3, rel=2e-4)
v.check("alpha_2(MZ) = alpha_EM/sin^2 theta_W", ALPHA2, 0.033712, rel=2e-4)
v.check("alpha_2^{-1}(MZ) body value", ALPHA2_INV, 29.66, rel=2e-4)
v.check(
    "alpha_2^{-1}(MZ) abstract value 33.05",
    ALPHA2_INV,
    33.05,
    rel=5e-3,
    detail="Expected fail: alpha_EM/sin^2(theta_W) gives about 29.66, not 33.05.",
)
v.check("alpha_s^{-1}(MZ) = 1/0.1179", ALPHA_S_INV_MZ, 8.482, rel=5e-5)

EZ = spectral_e(91_187.6)
Et = spectral_e(172_690)
Eb = spectral_e(4_180)
Ec = spectral_e(1_270)
Epl = spectral_e(1.2209e22)

v.check("E_Z from spectral formula", EZ, 18.384, rel=5e-4)
v.check("E_t from spectral formula", Et, 19.182, rel=5e-4)
v.check(
    "E_b from spectral formula vs P90 threshold table",
    Eb,
    17.530,
    rel=5e-4,
    detail="Expected fail: E(4180 MeV) is about 14.498 under Eq. (spectral).",
)
v.check(
    "E_c from spectral formula vs P90 threshold table",
    Ec,
    16.136,
    rel=5e-4,
    detail="Expected fail: E(1270 MeV) is about 12.996 under Eq. (spectral).",
)
v.check("E_Pl from spectral formula", Epl, 68.096, rel=2e-3)

b2 = 19 / 6
b3 = 7
delta_e = (ALPHA2_INV - ALPHA_S_INV_MZ) * 2 * PI / ((b3 - b2) * MU)
egut = EZ + delta_e

v.check("E6 unification Delta E", delta_e, 43.74, rel=5e-4)
v.check("E6 unification E_GUT", egut, 62.12, rel=5e-4)

mgut_mev = M_E * math.exp(MU * (egut - PI))
mgut_gev = mgut_mev / 1000
v.check(
    "M_GUT from E_GUT spectral map",
    mgut_gev,
    8.5e17,
    rel=5e-2,
    detail="Expected fail: E_GUT ~= 62.14 maps to about 1.08e17 GeV with Eq. (spectral).",
)
v.record(
    "M_GUT computed value is about 1.08e17 GeV",
    0.9e17 < mgut_gev < 1.3e17,
    f"{mgut_gev:.4e} GeV",
    "1.08e17 GeV",
)

alpha_gut_inv_from_s = ALPHA_S_INV_MZ + b3 * MU / (2 * PI) * delta_e
alpha_gut_inv_from_2 = ALPHA2_INV + b2 * MU / (2 * PI) * delta_e
v.check("alpha_GUT^{-1} from SU(3) running", alpha_gut_inv_from_s, 47.14, rel=5e-4)
v.check("alpha_GUT^{-1} from SU(2) running", alpha_gut_inv_from_2, 47.14, rel=5e-4)
v.check("alpha_GUT = 1/47.14", 1 / alpha_gut_inv_from_s, 0.02121, rel=5e-4)

# Multi-threshold running above MZ: the paper uses E_t near 19.182 and obtains
# a total close to 38.72. With exact values the total remains close.
delta1 = (23 / 3) * MU / (2 * PI) * (Et - EZ)
delta2 = 7 * MU / (2 * PI) * (egut - Et)
total_delta = delta1 + delta2
v.check("top-threshold contribution Delta alpha_s^{-1}_1", delta1, 0.7727, rel=2e-2)
v.check("high-interval contribution Delta alpha_s^{-1}_2", delta2, 37.95, rel=2e-3)
v.check("multi-threshold total Delta alpha_s^{-1}", total_delta, 38.72, rel=2e-3)
v.check("multi-threshold alpha_s^{-1}(E_GUT)", ALPHA_S_INV_MZ + total_delta, 47.20, rel=2e-3)

f4_inv = 9 * MU0 / (4 * PI**2)
v.check("F4 boundary alpha_s^{-1} = 9 mu0/(4 pi^2)", f4_inv, 31.24, rel=5e-4)
v.check("F4 boundary alpha_s", 1 / f4_inv, 0.032, rel=5e-4)

sys.exit(v.summary())

