#!/usr/bin/env python3
"""
verify_P106.py -- Addendum 106: strong-coupling closure from confinement.

This verifier checks the BREATH_PERIOD confinement-scale arithmetic, the
G2 root-ratio boundary condition numerics, and the multi-threshold 1-loop
spectral running in 106_Addendum_StrongCouplingClosure.tex.

The one-loop arithmetic is internally reproducible and lands at
alpha_s(MZ) ~= 0.11862. The flagged issues are proof/status claims: the
root-ratio boundary condition is an asserted matching condition rather than
a derivation, the running starts from alpha_s=sqrt(3) in a non-perturbative
region, the uniqueness of the BREATH scale is not proved by the displayed
calculation, and the higher-loop correction estimate is not produced by the
simple formula over the full interval.
"""

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: tolerance logic inherited byte-identical from
    verify_common.Verifier; only the output layer is modernised."""

    def __init__(self, name: str) -> None:
        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 = f"{label} -- {detail}" if detail else label
        print(f"  [{'PASS' if ok else 'FAIL'}] {n:>2}. {desc}")
        if computed != "" or claimed != "":
            print(f"        computed: {computed}")
            print(f"        claimed : {claimed}")
        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("P106 -- Strong Coupling Closure")

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

PI = math.pi
M_E = 0.51099895
M_Z = 91_187.6
M_C = 1_275.0
M_B = 4_180.0
PDG_ALPHA_S = 0.1179
PDG_SIGMA = 0.0009

MU0 = 4 * PI**3 + PI**2 + PI
MU1 = 16 * PI**3 / 5 + 3 * PI**2 / 4 + 2 * PI / 3
MU = MU1 / MU0
BREATH = PI * MU0
M_CONF = BREATH * M_E
E_CONF = PI + math.log(BREATH) / MU


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


def b0(nf: int) -> float:
    return 11 - 2 * nf / 3


def slope(nf: int) -> float:
    return b0(nf) * MU / (2 * PI)


E_Z = spectral_e(M_Z)
E_C = spectral_e(M_C)
E_B = spectral_e(M_B)
midpoint = 0.5 * (PI + E_Z)
root_ratio = math.sqrt(3)
alpha_inv_conf = 1 / root_ratio

delta1 = slope(3) * (E_C - E_CONF)
delta2 = slope(4) * (E_B - E_C)
delta3 = slope(5) * (E_Z - E_B)
alpha_inv_mz = alpha_inv_conf + delta1 + delta2 + delta3
alpha_mz = 1 / alpha_inv_mz

v.check("mu0", MU0, 137.036, rel=3e-6)
v.check("MU = mu1/mu0", MU, 0.7934, rel=8e-5)
v.check("BREATH = pi*mu0", BREATH, 430.51, rel=5e-5)
v.check("m_conf = BREATH*m_e MeV", M_CONF, 219.99, rel=5e-5)
v.check("E_conf", E_CONF, 10.786, rel=5e-5)
v.check("E_Z", E_Z, 18.382, rel=2e-4)
v.check("spectral midpoint", midpoint, 10.762, rel=1e-4)
v.check("E_conf midpoint difference", E_CONF - midpoint, 0.024, rel=5e-2)
v.check("midpoint fractional gap percent", 100 * abs(E_CONF - midpoint) / (E_Z - PI), 0.16, rel=3e-2)

v.check("G2 long/short root ratio", root_ratio, 1.73205, rel=3e-6)
v.check("cot(pi/6)", 1 / math.tan(PI / 6), root_ratio, rel=1e-12)
v.check("alpha_s inverse at confinement", alpha_inv_conf, 0.5774, rel=1e-4)

v.check("E_c threshold", E_C, 13.001, rel=5e-5)
v.check("E_b threshold", E_B, 14.497, rel=8e-5)
v.check("slope nf=3", slope(3), 1.1365, rel=2e-4)
v.check("slope nf=4", slope(4), 1.0523, rel=2e-4)
v.check("slope nf=5", slope(5), 0.9681, rel=2e-4)
v.check("Delta1 nf=3", delta1, 2.517, rel=5e-4)
v.check("Delta2 nf=4", delta2, 1.575, rel=5e-4)
v.check("Delta3 nf=5", delta3, 3.761, rel=5e-4)
v.check("sum of running deltas", delta1 + delta2 + delta3, 7.853, rel=5e-5)
v.check("alpha_s inverse MZ", alpha_inv_mz, 8.430, rel=5e-5)
v.check("alpha_s MZ", alpha_mz, 0.1186, rel=2e-4)
v.check("alpha_s residual percent", 100 * (alpha_mz - PDG_ALPHA_S) / PDG_ALPHA_S, 0.61, rel=2e-2)
v.check("alpha_s residual sigma", (alpha_mz - PDG_ALPHA_S) / PDG_SIGMA, 0.80, rel=2e-2)
v.check("PDG alpha_s inverse", 1 / PDG_ALPHA_S, 8.482, rel=8e-5)
v.check("PDG alpha_s inverse uncertainty", PDG_SIGMA / PDG_ALPHA_S**2, 0.064, rel=2e-2)

v.record(
    "BREATH_PERIOD scale uniqueness is proven by enumeration/search",
    False,
    "the paper identifies pi*mu0*m_e as natural but does not enumerate all kernel-level scales in [pi,E_Z]",
    "unique kernel-synchronised scale",
    "Expected proof-audit fail: uniqueness is asserted, not established by a solver/search.",
)
v.record(
    "G2 root-ratio boundary condition is derived from matching equations",
    False,
    "root-length ratio sqrt(3) is correct, but alpha_s(E_conf)=sqrt(3) is a boundary postulate",
    "derived theorem",
    "Expected proof-audit fail: no RG/matching calculation derives equality of the coupling to the root-length ratio.",
)
v.record(
    "1-loop perturbative running is valid from alpha_s(E_conf)=sqrt(3)",
    root_ratio < 0.3,
    f"starting boundary alpha_s={root_ratio:.3f} at m_conf≈{M_CONF:.1f} MeV",
    "perturbative 1-loop closure",
    "Expected status fail: the numerical extrapolation lands perturbative at M_Z, but the starting point is non-perturbative.",
)

b1_nf5 = 102 - 38 * 5 / 3
displayed_two_loop_full = -b1_nf5 / (2 * PI * b0(5) ** 2) * alpha_mz**2 * (E_Z - E_CONF)
v.check(
    "displayed 2-loop estimate over full E_conf-to-E_Z interval",
    displayed_two_loop_full,
    -0.003,
    rel=2e-1,
    detail="Expected fail: applying the displayed formula over the full interval gives about -0.011, not -0.003.",
)
v.record(
    "3-through-5-loop correction claim is derived in this paper",
    "3-through-5-loop\ncorrections add back" not in TEX,
    "paper states higher loops add back +0.003--+0.005 but does not compute them",
    "derived multi-loop correction",
    "Expected status fail: this remains an external QCD expectation, not a TOE verifier result.",
)
v.record(
    "OP1 all-order closure is complete",
    "OP1-NLO" not in TEX,
    "paper defines OP1-NLO for b1 and higher orders",
    "all-order closure",
    "Expected status fail: the paper closes only the conditional 1-loop version.",
)

sys.exit(v.summary())
