#!/usr/bin/env python3
"""AP49 -- "The Hold" -- independent verification script.

Reproduces, from CODATA 2022 alone, AP30's proton-to-electron mass ratio
series closed to all orders -- the chain of holders, each order the
previous times r = 16*alpha/1836 -- and checks the closed form against
both CODATA 2022 and the independent 2025 H2+ spectroscopy value. Also
reproduces the two kill switches that are still live (KS-HOLD.1, the
closed form's own kill threshold; KS-HOLD.3, the ambiguity between the
chain's two possible bases) and the one this paper pays (AP30's KS-30.3).

    python3 verify_ap49.py

No dependencies beyond the Python 3 standard library. No network access.

Source: AP49_The_Hold_FINAL_v1_0.md sections 2, 4, 5, 7. Full text of the
state of record: lucid.rodeo/prereg/ap49/
"""
from __future__ import annotations

# --------------------------------------------------------------------------- #
# CODATA 2022 -- the only measured input to the prediction itself
# --------------------------------------------------------------------------- #
ALPHA = 7.2973525643e-3          # fine-structure constant, CODATA 2022
MP_ME_CODATA = 1836.152673426    # measured proton/electron mass ratio, CODATA 2022
CODATA_U = 3.2e-8                # its 1-sigma uncertainty

# Independent check: H2+ spectroscopy, Alighanbari, Schenkel, Korobov,
# Schiller, Nature 644, 69 (2025), doi 10.1038/s41586-025-09306-2.
MP_ME_H2PLUS = 1836.152673414
H2PLUS_U = 4.7e-8

STATIC = 1836                    # AP30's static resistance, 1764 + 63 + 9
CHANNELS = 21                    # AP30's 21 channels (the repair's coupling count)
LEAK_DIVISOR = 84 * 3.141592653589793  # AP30's isotropic-leakage normalisation, 84*pi
HOLD = 16                        # this paper's decomposed count, 4 (conditions) x 4 (dimensions)


def sigma(predicted: float, measured: float, u: float) -> float:
    """(measured - predicted) / u -- the paper's own convention (Sec. 5): the
    residual is what the sky says, measurement minus prediction."""
    return (measured - predicted) / u


def main() -> int:
    bar = "=" * 76
    print(bar)
    print("AP49 -- The Hold -- independent verification (CODATA 2022, stdlib only)")
    print(bar)

    repair = CHANNELS * ALPHA * (1 - 1 / LEAK_DIVISOR)
    r = HOLD * ALPHA / STATIC

    print("\nThe repair, AP30's first-order term:")
    print(f"  21*alpha*(1 - 1/(84*pi)) = {repair:.9f}  (claimed 0.152663699)")
    print(f"\nThe repair's share, r = 16*alpha/1836:")
    print(f"  r = {r:.7e}  (claimed 6.3593e-05)")

    # The chain: coefficient at order n (n>=2) is CHANNELS * HOLD**(n-1) / STATIC**(n-1),
    # i.e. term_n = repair's bare coupling (21*alpha) * r**(n-1).
    bare = CHANNELS * ALPHA
    terms = [repair]
    for n in range(2, 6):
        terms.append(bare * r ** (n - 1))

    labels = ["alpha  (the repair)", "alpha^2 (2nd holder)", "alpha^3 (3rd holder)",
              "alpha^4 (4th holder)", "alpha^5 (5th holder)"]
    print("\nThe chain, order by order (each holder = previous holder's coupling * r):")
    for lbl, t in zip(labels, terms):
        print(f"  {lbl:<22} {t:.6e}")

    # Closed form: static + repair + bare*(r + r^2 + r^3 + ...) = static + repair + bare*r/(1-r)
    tail_closed = bare * r / (1 - r)
    tail_truncated_at_2nd = terms[1]
    third_order_and_beyond = tail_closed - tail_truncated_at_2nd

    d_closed = STATIC + repair + tail_closed
    d_truncated = STATIC + repair + tail_truncated_at_2nd  # AP30/2-Aug D, series stopped at alpha^2

    print(f"\nThe tail, closed form: 21*alpha*r/(1-r) = {tail_closed:.7e}  (claimed 9.7459657e-06)")
    print(f"Third order and everything beyond it: {third_order_and_beyond:.3e}  (claimed 6.20e-10)")

    print(f"\nD (2 August, truncated at alpha^2)     = {d_truncated:.12f}  (claimed 1836.152673444331)")
    print(f"D_closed (this paper, all orders)      = {d_closed:.12f}  (claimed 1836.152673444951)")

    # c3, the third-order coefficient, sign stated in advance.
    c3 = CHANNELS * HOLD ** 2 / STATIC ** 2
    print(f"\nc3 = 21*16^2/1836^2 = {c3:.6e}  (claimed +1.595e-03, sign positive)")

    # Against measurement.
    sig_codata = sigma(d_closed, MP_ME_CODATA, CODATA_U)
    sig_h2plus = sigma(d_closed, MP_ME_H2PLUS, H2PLUS_U)
    print(f"\nAgainst CODATA 2022 ({MP_ME_CODATA}({round(CODATA_U*1e9)})):")
    print(f"  residual (measured - predicted) = {MP_ME_CODATA - d_closed:.3e}  (claimed -1.90e-08)")
    print(f"  sigma = {sig_codata:+.2f}  (claimed -0.59)")
    print(f"\nAgainst H2+ 2025 ({MP_ME_H2PLUS}({round(H2PLUS_U*1e9)})):")
    print(f"  residual (measured - predicted) = {MP_ME_H2PLUS - d_closed:.3e}  (claimed -3.10e-08)")
    print(f"  sigma = {sig_h2plus:+.2f}  (claimed -0.66)")

    # KS-HOLD.1 -- the kill thresholds, holding the central value fixed and tightening u.
    print(f"\nKS-HOLD.1 -- the closed form. LIVE -- dies at 3 sigma once the")
    print(f"measurement's uncertainty reaches the threshold below, central value unchanged:")
    current_rel_u = CODATA_U / MP_ME_CODATA
    print(f"  current relative uncertainty       = {current_rel_u:.3e}  ({current_rel_u*1e12:.1f} ppt)  (claimed 17.4 ppt)")
    for target_sigma in (3, 5):
        u_needed = abs(MP_ME_CODATA - d_closed) / target_sigma
        rel_u_needed = u_needed / MP_ME_CODATA
        print(f"  {target_sigma}-sigma threshold                 = {rel_u_needed*1e12:.2f} ppt"
              f"  (claimed {'3.4' if target_sigma == 3 else '2.1'} ppt)")

    # KS-HOLD.3 -- the base ambiguity: bare coupling (this paper) vs the repair net of its leak.
    leaked_repair = CHANNELS * ALPHA * (1 - 1 / LEAK_DIVISOR) * (1 - 1 / LEAK_DIVISOR)
    r_from_leaked = HOLD * ALPHA / STATIC  # r itself is unaffected; only the bare/leaked base changes
    tail_leaked = (CHANNELS * ALPHA * (1 - 1 / LEAK_DIVISOR)) * r_from_leaked / (1 - r_from_leaked)
    d_leaked = STATIC + repair + tail_leaked
    print(f"\nKS-HOLD.3 -- the base of the chain. Two possible bases for the second holder:")
    print(f"  bare coupling  21*alpha            -> D_closed = {d_closed:.9f}  (claimed 1836.152673445)")
    print(f"  net of its own leak (21*alpha*(1-1/84pi)) -> D_leaked = {d_leaked:.9f}  (claimed 1836.152673408)")
    print(f"  the two are {(d_closed - d_leaked)*1e8:.1f}e-08 apart  (claimed 3.7e-08)")

    print(f"\n{bar}")
    print(f"KS-30.3 (AP30): PAID -- the chain converges by construction, ratio r = {r:.3e} << 1.")
    print(f"KS-HOLD.1: LIVE -- D_closed = {d_closed:.9f}, {sig_codata:+.2f} sigma from CODATA 2022.")
    print(f"KS-HOLD.2: LIVE -- structural, not testable by this script (see prereg/ap49/).")
    print(f"KS-HOLD.3: LIVE -- {abs(sig_codata):.2f} sigma from the bare base, "
          f"{sigma(d_leaked, MP_ME_CODATA, CODATA_U):+.2f} sigma from the leaked base.")
    print(bar)

    # Sanity gate: the paper's claimed value should reproduce to high precision.
    claimed = 1836.152673444951
    ok = abs(d_closed - claimed) < 1e-9 and abs(sig_codata - (-0.59)) < 0.01
    return 0 if ok else 1


if __name__ == "__main__":
    raise SystemExit(main())
