#!/usr/bin/env python3
"""
verify_P045.py -- Addendum 45: Quark Orbit Matching.

This verifier recomputes the quark energy/mass table, Cabibbo angle,
top/charm ratio reformulation, moment-log spectrum, and selected structural
claims in 45_Addendum_QuarkOrbitMatching.tex.

The main numerical table mostly reproduces. The flagged items are internal
consistency/proof-status issues: the P41-error explanation is not compatible
with the paper's mass formula, the later top/charm ratio paragraph uses a
different PDG input set than the table and does not correspond to the quoted
top-mass residual, the shifted mass formula is misread in the D-moment section,
and the proposed OP-B' Jordan triple product is zero on off-diagonal Peirce
components in the standard special-Jordan calculation.
"""

import math
import sys
from pathlib import Path

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


class ModernVerifier(Verifier):
    """Local adapter: modern check-line output format. Tolerance logic is
    inherited unchanged from verify_common.Verifier; only printing differs.
    Computed/claimed values stay as indented info lines."""

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

    def summary(self) -> int:
        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("P045 -- Quark Orbit Matching")

PI = math.pi
M_E = 0.511  # MeV, as stated in P45 Eq. (1).
MU0 = 4 * PI**3 + PI**2 + PI
MU1 = 16 * PI**3 / 5 + 3 * PI**2 / 4 + 2 * PI / 3
MU = MU1 / MU0
N_IM = 7
N_C = 3

# Inputs implied by the numerical table. The top empirical energy 19.1884
# matches 172.69 GeV, while the later mass-ratio paragraph switches to
# 172.760 GeV and m_c=1275 MeV.
PDG_TABLE = {
    "u": 2.16,
    "d": 4.70,
    "s": 93.4,
    "c": 1270.0,
    "b": 4180.0,
    "t": 172_690.0,
}

E_FORMULA = {
    "d": math.log(MU1) / MU,
    "s": PI**2 - 1 / N_IM,
    "b": PI ** (N_IM / N_C),
    "u": PI ** (N_IM / (N_IM - N_C + 1)),
    "c": PI**2 + PI,
    "t": PI**2 + PI + math.log(MU0) / MU,
}


def mass_from_e(energy: float) -> float:
    return M_E * math.exp(MU * (energy - PI))


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


def residual_pct(pred: float, actual: float) -> float:
    return 100 * (pred - actual) / actual


v.check("mu0 = 4*pi^3 + pi^2 + pi", MU0, 137.036304, rel=5e-9)
v.check("mu1 = 16*pi^3/5 + 3*pi^2/4 + 2*pi/3", MU1, 108.716684, rel=5e-9)
v.check("MU = mu1/mu0", MU, 0.793342, rel=5e-7)
v.check("non-bulk sub-integral pi^2 + pi", PI**2 + PI, 13.011, rel=2e-5)
v.check("G2 dimension 2*NIm", 2 * N_IM, 14, rel=0)
v.check("G2 Coxeter relation 2*(h+1) with h=6", 2 * (6 + 1), 14, rel=0)

claimed_empirical_e = {
    "d": 5.9386,
    "s": 9.7066,
    "b": 14.4979,
    "u": 4.9586,
    "c": 12.9963,
    "t": 19.1884,
}
for quark, claimed in claimed_empirical_e.items():
    v.check(
        f"E_{quark} empirical from table PDG mass",
        e_from_mass(PDG_TABLE[quark]),
        claimed,
        rel=4e-5,
    )

claimed_formula_e = {
    "d": 5.9101,
    "s": 9.7267,
    "b": 14.4549,
    "u": 4.9660,
    "c": 13.0112,
    "t": 19.2131,
}
for quark, claimed in claimed_formula_e.items():
    v.check(f"E_{quark} TOE formula", E_FORMULA[quark], claimed, rel=4e-5)

claimed_masses = {
    "d": 4.60,
    "s": 94.9,
    "b": 4040.0,
    "u": 2.17,
    "c": 1285.0,
    "t": 176.1e3,
}
for quark, claimed in claimed_masses.items():
    v.check(
        f"m_{quark} from P45 mass formula",
        mass_from_e(E_FORMULA[quark]),
        claimed,
        rel=2e-3 if quark in {"d", "u"} else 8e-4,
    )

claimed_mass_errors = {
    "d": -2.2,
    "s": 1.6,
    "b": -3.3,
    "u": 0.6,
    "c": 1.2,
    "t": 2.0,
}
for quark, claimed in claimed_mass_errors.items():
    v.check(
        f"{quark} mass residual percent",
        residual_pct(mass_from_e(E_FORMULA[quark]), PDG_TABLE[quark]),
        claimed,
        rel=6e-2 if quark in {"b", "t"} else 8e-2,
    )

cabibbo = math.sin(PI / 14)
v.check("Cabibbo sin(pi/14)", cabibbo, 0.22252, rel=5e-6)
v.check("Cabibbo residual percent", residual_pct(cabibbo, 0.22431), -0.80, rel=2e-2)

top_gap = math.log(MU0) / MU
pdg_gap = e_from_mass(PDG_TABLE["t"]) - e_from_mass(PDG_TABLE["c"])
v.check("top/charm predicted gap ln(mu0)/MU", top_gap, 6.202, rel=2e-5)
v.check("top/charm table PDG gap", pdg_gap, 6.192, rel=5e-5)
v.check("top/charm gap discrepancy percent", residual_pct(top_gap, pdg_gap), 0.16, rel=5e-2)
v.check(
    "top/charm E_t discrepancy percent",
    residual_pct(E_FORMULA["t"], e_from_mass(PDG_TABLE["t"])),
    0.13,
    rel=2e-2,
)

mass_at_intermediate = mass_from_e(18.626)
v.check(
    "P41 E_t=18.626 route gives +8.7 percent top error",
    residual_pct(mass_at_intermediate, PDG_TABLE["t"]),
    8.7,
    rel=2e-1,
    detail="Expected fail: under Eq. (1), E_t=18.626 gives about 110.5 GeV, a -36% error, not +8.7%.",
)

later_ratio = 172_760.0 / 1275.0
table_ratio = PDG_TABLE["t"] / PDG_TABLE["c"]
v.check("later-section PDG ratio 172760/1275", later_ratio, 135.50, rel=2e-5)
v.check("later-section ratio discrepancy vs mu0", residual_pct(MU0, later_ratio), 1.1, rel=5e-2)
v.record(
    "later top/charm ratio uses same PDG inputs as numerical table",
    abs(later_ratio - table_ratio) < 1e-9,
    f"later={later_ratio:.6f}, table={table_ratio:.6f}",
    "same ratio",
    "Expected fail: Section 6 switches from the table's 172.69/1270 inputs to 172.760/1275.",
)
v.check(
    "later ratio discrepancy corresponds to +1.9 percent tabulated top residual",
    residual_pct(MU0, later_ratio),
    1.9,
    rel=5e-2,
    detail="Expected fail: 172760/1275 differs from mu0 by about +1.14%, not the +1.9% top-mass residual from the formula table.",
)

for k, claimed_mu, claimed_g in [
    (0, 137.036, 6.2019),
    (1, 108.717, 5.9101),
    (2, 90.176, 5.6744),
    (3, 77.063, 5.4764),
    (4, 67.290, 5.3054),
    (5, 59.721, 5.1550),
]:
    mu_k = 16 * PI**3 / (k + 4) + 3 * PI**2 / (k + 3) + 2 * PI / (k + 2)
    g_k = math.log(mu_k) / MU
    v.check(f"moment mu_{k}", mu_k, claimed_mu, rel=8e-6)
    v.check(f"G_{k} = ln(mu_{k})/MU", g_k, claimed_g, rel=2e-5)

v.check("G0 - G1 exact shift", math.log(MU0 / MU1) / MU, 0.2918, rel=2e-4)
v.check("-ln(MU)/MU identity", -math.log(MU) / MU, math.log(MU0 / MU1) / MU, rel=1e-12)

mass_d_ratio = math.exp(MU * E_FORMULA["d"] - MU * PI)
v.check("down mass ratio identity mu1/exp(MU*pi)", mass_d_ratio, MU1 / math.exp(MU * PI), rel=1e-12)

mass_ratio_at_pi = mass_from_e(PI) / M_E
v.check(
    "exp(MU*pi) equals m(E=pi)/m_e under Eq. (1)",
    math.exp(MU * PI),
    mass_ratio_at_pi,
    rel=1e-6,
    detail="Expected fail: Eq. (1) is shifted, so E=pi gives m/m_e=1; exp(MU*pi) is the inverse E=0 factor.",
)
rewritten_down_mass = MU1 * M_E**2 / mass_from_e(PI)
v.check(
    "D-moment rewrite mu1*m_e^2/m(E=pi) equals m_d",
    rewritten_down_mass,
    mass_from_e(E_FORMULA["d"]),
    rel=1e-6,
    detail="Expected fail: the denominator should be exp(MU*pi), equivalently m_e/m(E=0), not m(E=pi)/m_e.",
)
v.check("correct D-moment rewrite m_d = mu1*m(E=0)", MU1 * mass_from_e(0), mass_from_e(E_FORMULA["d"]), rel=1e-12)
v.check("Boltzmann weight exp(-MU*G0)", math.exp(-MU * (math.log(MU0) / MU)), 1 / MU0, rel=1e-12)
v.check("Boltzmann weight exp(-MU*G1)", math.exp(-MU * (math.log(MU1) / MU)), 1 / MU1, rel=1e-12)

v.check("bottom exponent NIm/Nc", N_IM / N_C, 7 / 3, rel=0)
v.check("up exponent NIm/(NIm-Nc+1)", N_IM / (N_IM - N_C + 1), 7 / 5, rel=0)
v.check("SU3/SU2 dimension gap", 8 - 3, N_IM - N_C + 1, rel=0)
v.check("strange one-Fano descent pi^2 - 1/7", PI**2 - 1 / N_IM, E_FORMULA["s"], rel=0)

fermion_energies = {
    "e": PI,
    "mu": e_from_mass(105.6583755),
    "tau": e_from_mass(1776.86),
    **{q: e_from_mass(m) for q, m in PDG_TABLE.items()},
}
lattice_hits = []
lattice_misses = []
for n in range(0, 12):
    value = PI ** (n / N_C)
    best_name, best_energy = min(
        fermion_energies.items(), key=lambda item: abs(value / item[1] - 1)
    )
    miss = abs(residual_pct(value, best_energy))
    if n in {N_C, 2 * N_C, N_IM}:
        lattice_hits.append((n, round(miss, 4), best_name))
    else:
        lattice_misses.append((n, round(miss, 4), best_name))
v.record("pi^(n/3) claimed occupied nodes are within 1 percent", all(miss < 1 for _, miss, _ in lattice_hits), lattice_hits, "n=3,6,7")
v.record("other pi^(n/3) nodes miss by more than 7 percent through n=11", all(miss > 7 for _, miss, _ in lattice_misses), lattice_misses, ">7%")

v.check("Z3 clock V1 dimension", 3, 3, rel=0)
v.check("Z3 clock V_omega dimension", 8, 8, rel=0)
v.check("Z3 clock V_omega2 dimension", 16, 16, rel=0)
v.check("Z3 clock total complex dimension", 3 + 8 + 16, 27, rel=0)
v.check("V_omega2/V1 dimension ratio", 16 / 3, 16 / 3, rel=0)
v.check("V_omega/V1 dimension ratio", 8 / 3, 8 / 3, rel=0)
v.record("Z3 sector dimension ratio is not mu0", abs((16 / 3) - MU0) > 100, 16 / 3, MU0)

v.record(
    "Fano-plane count '7 lines and 5 complementary triples' is literal",
    False,
    "Fano plane: 7 lines of size 3; line complements have size 4; non-line triples count C(7,3)-7 = 28.",
    "7 lines + 5 complementary triples",
    "Expected proof-audit fail: the stated root/Fano counting is not standard literal Fano-plane combinatorics.",
)
v.record(
    "OP-B' Phi(y)={alpha3,y,alpha3} can have trace-norm squared mu0 on V_omega2",
    False,
    "For a diagonal idempotent p=E33, the special-Jordan triple product {p,y,p}=pyp is zero for off-diagonal y.",
    "||Phi||^2 = mu0",
    "Expected proof-audit fail: as written, the proposed map does not send off-diagonal V_omega2 to a nonzero V1 invariant.",
)

sys.exit(v.summary())
