#!/usr/bin/env python3
"""AP47 -- "The Flip" -- independent verification script.

Reproduces, from CODATA 2022 alone, every number behind the two neutron-proton
mass-difference rows on lucid.rodeo/prereg/:

  KS-NPP.1  the ORIGINAL, uncorrected prediction. FIRED 2026-08-02. Stays fired.
            This script does not hide that -- it recomputes the kill, on purpose.
  KS-FLIP.1 AP47's correction ("The Flip"). LOCKED 2026-09-03 on the420code-proof
            (tag ap47-locked-2026-09-03). Stands beside the fired row; does not
            repair it.

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

    python3 verify_ap47.py

Source: AP47_The_Flip_FINAL_v3.md sections 0.9, 5, 6, 7, and
ERRATA_FLIP_2026-09-01.md (the bundle's own corrections ledger). Full text of
the state of record: lucid.rodeo/prereg/ap47/
"""
from __future__ import annotations

import math

# --------------------------------------------------------------------------- #
# CODATA 2022 -- the only measured inputs
# --------------------------------------------------------------------------- #
ALPHA = 7.2973525643e-3     # fine-structure constant
MN_ME = 1838.68366200       # neutron/electron mass ratio
MP_ME = 1836.152673426      # proton/electron mass ratio
U_DELTA = 7.4e-7            # audited 1-sigma on (m_n/m_e - m_p/m_e), in m_e (0.29 ppm)
U_MP_ME = 3.2e-8            # 1-sigma on m_p/m_e, in m_e
PI = math.pi


def sigma(value: float, measured: float, u: float) -> float:
    return (value - measured) / u


def delta_real_for(divisor_n: float, delta_bare: float) -> float:
    """Delta_bare discounted by the hold-cost fraction alpha^2/N."""
    return delta_bare / (1 + ALPHA ** 2 / divisor_n)


def main() -> int:
    delta_meas = MN_ME - MP_ME

    # KS-NPP.1 -- the original claim: the flip priced as free.
    delta_bare = 3 * (1 - 1 / (2 * PI)) + ALPHA * (1 + 1 / (2 * PI))
    sigma_bare = sigma(delta_bare, delta_meas, U_DELTA)

    # KS-FLIP.1 -- AP47's correction: a held distinction costs a continuous
    # second-order tax, f2 = alpha^2/(8*pi), on the booking of the difference.
    f2 = ALPHA ** 2 / (8 * PI)
    delta_real = delta_bare / (1 + f2)
    sigma_real = sigma(delta_real, delta_meas, U_DELTA)

    # Section 5 -- the elimination. Required divisor to land exactly on Delta_meas
    # (errata item 9's corrected formula -- NOT the reviewer's flipped display slip).
    delta_needed = delta_bare - delta_meas
    n_required = ALPHA ** 2 * delta_bare / delta_needed

    # Section 7 -- the ground state must reject the cost, or KS-FLIP.4 fires.
    proton_shift = MP_ME * f2
    proton_sigma = proton_shift / U_MP_ME

    bar = "=" * 76
    print(bar)
    print("AP47 -- The Flip -- independent verification (CODATA 2022, stdlib only)")
    print(bar)

    print("\nKS-NPP.1 -- the ORIGINAL bare-difference prediction. FIRED 2026-08-02.")
    print(f"  Delta_bare = 3(1-1/2pi) + alpha(1+1/2pi)  = {delta_bare:.11f} m_e")
    print(f"  Delta_meas (CODATA 2022, exact difference) = {delta_meas:.9f} m_e")
    print(f"  sigma = {sigma_bare:+.3f}   bar = audited 1-sigma ({U_DELTA:.1e} m_e)")
    print(f"  -> {'FIRED / DEAD' if abs(sigma_bare) > 1 else 'would survive'} -- kept in this"
          " script deliberately, never repaired.")

    print("\nKS-FLIP.1 -- AP47's correction. LOCKED 2026-09-03.")
    print(f"  f2 = alpha^2 / (8*pi)                      = {f2:.6e}")
    print(f"  Delta_real = Delta_bare / (1 + f2)          = {delta_real:.11f} m_e")
    print(f"  sigma = {sigma_real:+.4f}   bar = audited 1-sigma ({U_DELTA:.1e} m_e)")
    print(f"  -> {'LANDS' if abs(sigma_real) <= 1 else 'FAIL'} -- stands beside the fired row"
          " above, does not repair it.")

    print("\nSection 5 -- the elimination (candidate divisors for Delta_bare/(1+alpha^2/N)):")
    print(f"  {'candidate':<22}{'N':>12}{'sigma':>12}   standing")
    candidates = {
        "support 2 (2x4xpi)": 2 * 4 * PI,
        "support 3 (3x4xpi)": 3 * 4 * PI,
        "support 6 (6x4xpi)": 6 * 4 * PI,
        "support 18 (18x4xpi)": 18 * 4 * PI,
        "support 21 (21x4xpi)": 21 * 4 * PI,
        "3D count (2x3xpi)": 2 * 3 * PI,
        "9pi": 9 * PI,
    }
    for label, divisor_n in candidates.items():
        dr = delta_real_for(divisor_n, delta_bare)
        s = sigma(dr, delta_meas, U_DELTA)
        standing = "LANDS (within 1-sigma)" if abs(s) <= 1 else "dead"
        print(f"  {label:<22}{divisor_n:>12.4f}{s:>12.3f}   {standing}")
    print(f"  Divisor required to land exactly: {n_required:.4f}"
          " -- only the integer support=2 (giving 8pi=25.13) is structurally motivated.")

    print("\nSection 7 -- the proton-elimination check (ground state must reject the cost):")
    print(f"  proton shift = m_p/m_e * f2 = {proton_shift:.8f} m_e")
    print(f"  sigma = {proton_sigma:,.1f}"
          "   (an early draft miscalculated this as ~223 sigma on an unnamed coarser bar"
          " -- wrong; corrected here, see ERRATA_FLIP_2026-09-01.md item 2)")

    print(f"\n{bar}")
    print(f"KS-NPP.1: FIRED at {sigma_bare:+.2f} sigma. Stays fired -- not touched by this script.")
    print(f"KS-FLIP.1: lands at {sigma_real:+.4f} sigma. LOCKED 2026-09-03.")
    print(bar)

    # Exit 0 only reports "the script ran and both rows are exactly what the
    # paper claims" -- it is NOT a claim that KS-NPP.1 passed. See the printed
    # report above, which shows FIRED explicitly and always will.
    fired_as_expected = abs(sigma_bare) > 1
    flip_lands_as_expected = abs(sigma_real) <= 1
    return 0 if (fired_as_expected and flip_lands_as_expected) else 1


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