#!/usr/bin/env python3
"""
verify_P010.py -- Paper 10: three-fourths boundary correction.

This verifier checks the numeric approximation in
toe/10_Paper_ThreeFourthsCorrection.tex.  The base formula, moment values,
3/4 corrected alpha value, and rational-scan claim mostly reproduce when the
target alpha value is used inside the correction term.  The flagged issues are
status/internal-consistency problems: the formula is circular unless alpha is
solved self-consistently, the theoretical derivation of c=3/4 is explicitly
left open, the continuous-optimization remark contradicts the analytic c_opt,
one alternative "worse" factor is stale, the alpha^4 term is not ~1e-8, and
the no-fourth-family proof overreaches the Z3/topology argument inherited from
P6.
"""

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("P010 -- Three-Fourths Boundary Correction")

ROOT = Path(__file__).resolve().parents[2]
TEX = (ROOT / "toe" / "10_Paper_ThreeFourthsCorrection.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
MU2 = 16 * PI**3 / 6 + 3 * PI**2 / 5 + 2 * PI / 4
TARGET_INV = 137.036
CODATA_INV = 137.035999084
ALPHA_TARGET = 1.0 / TARGET_INV
BASE = 5**4 * (1.0 / PI - 1.0 / 10.0)


def pred(c: float, alpha_inv: float = TARGET_INV) -> float:
    return BASE * (1.0 + c * MU1 * (1.0 / alpha_inv) ** 2)


def rel_percent(value: float, target: float) -> float:
    return 100.0 * (value - target) / abs(target)


v.check("mu0", MU0, 137.036303776, rel=1e-12)
v.check("mu1", MU1, 108.716683780, rel=2e-12)
v.check("mu2", MU2, 90.175963448, rel=3e-12)
v.check("base formula", BASE, 136.443679, rel=1e-9)
v.check("base relative error percent", abs(rel_percent(BASE, TARGET_INV)), 0.432, rel=2e-3)
v.check("mu1 alpha^2 correction scale", MU1 * ALPHA_TARGET**2, 0.005789311, rel=5e-6)
v.check("3/4 correction factor", 1.0 + 0.75 * MU1 * ALPHA_TARGET**2, 1.004341983, rel=2e-8)
v.check("corrected alpha inverse", pred(0.75), 137.036114991, rel=5e-12)
v.check("corrected relative error percent", abs(rel_percent(pred(0.75), TARGET_INV)), 8.39e-5, rel=3e-3)

c_required = (TARGET_INV / BASE - 1.0) / (MU1 * ALPHA_TARGET**2)
v.check("required c from target 137.036", c_required, 0.749854426, rel=3e-9)
v.check("distance from 3/4", abs(c_required - 0.75), 1.43e-4, rel=3e-2)

best = []
for a in range(1, 21):
    for b in range(1, 21):
        c = a / b
        err = abs(pred(c) - TARGET_INV) / TARGET_INV
        best.append((err, c, a, b))
best.sort()
v.check("best rational scan value", best[0][1], 0.75, rel=1e-12)
v.check("best rational scan relative error", best[0][0], 8.4e-7, rel=2e-2)

err_34 = abs(rel_percent(pred(0.75), TARGET_INV))
err_23 = abs(rel_percent(pred(2.0 / 3.0), TARGET_INV))
err_1 = abs(rel_percent(pred(1.0), TARGET_INV))
err_43 = abs(rel_percent(pred(4.0 / 3.0), TARGET_INV))
v.check("c=2/3 error percent", err_23, 0.048, rel=2e-3)
v.check("c=2/3 worse factor", err_23 / err_34, 570, rel=5e-3)
v.check("c=1 error percent", err_1, 0.144, rel=2e-3)
v.check("c=1 worse factor", err_1 / err_34, 1700, rel=2e-2)
v.check("c=4/3 error percent", err_43, 0.432, rel=3e-1)
v.check(
    "c=4/3 worse factor",
    err_43 / err_34,
    5100,
    rel=5e-2,
    detail="Expected fail: exact ratio is about 4008 using the paper's target and rounded formula.",
)

x = 0.75 * MU1 * ALPHA_TARGET**2
v.check("nonperturbative vs first-order difference percent", 100.0 * ((1.0 / (1.0 - x)) - (1.0 + x)) / (1.0 + x), 0.002, rel=7e-2)
v.check(
    "alpha^4 second-order term",
    (9.0 / 16.0) * MU1**2 * ALPHA_TARGET**4,
    1e-8,
    rel=1.0,
    detail="Expected fail: the next term is about 1.9e-5, not order 1e-8.",
)
v.check("CODATA relative difference ppm", abs(pred(0.75) - CODATA_INV) / CODATA_INV * 1e6, 1.1, rel=3e-1)

v.record(
    "formula is zero-input rather than using target alpha on the RHS",
    False,
    computed="the correction term uses alpha^2; the numerical section evaluates it with alpha^{-1}=137.036",
    claimed="zero adjustable parameters / alpha inverse derived",
    detail="Expected status fail: a self-contained prediction should specify whether alpha is solved implicitly or imported.",
)
v.record(
    "alpha-cube derives alpha without alpha as input",
    "a_\\alpha = \\left(\\frac{\\alpha\\sqrt{5}}{96}\\right)" not in TEX,
    computed="the alpha-cube side length is defined in terms of alpha",
    claimed="alpha naturally incorporated by equilibrium geometry",
    detail="Expected circularity fail.",
)
v.record(
    "theoretical derivation of c=3/4 is closed",
    False,
    computed="remark states that a first-principles proof of exactly 3/4 remains open",
    claimed="five independent geometric derivations force 3/4",
    detail="Expected status fail.",
)
v.record(
    "continuous optimization gives c=0.750000000 and distance <1e-9",
    False,
    computed=f"analytic optimum from the printed objective is c={c_required:.9f}, distance {abs(c_required - 0.75):.3g}",
    claimed="continuous optimisation converges to 0.750000000 with distance <1e-9",
    detail="Expected internal-consistency fail.",
)
v.record(
    "Z3/family argument topologically forbids a fourth family",
    False,
    computed="Z3 has three representation labels, but representations can occur with multiplicity; P6 verifier also finds the family proof underderived",
    claimed="fourth fermion family topologically forbidden",
    detail="Expected proof-audit fail.",
)

sys.exit(v.summary())
