#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
verify_P343.py  --  A343 blast-radius audit of the A337 correction.

A337 retracted the identification "T_3B = j(tau)^(1/3)" as a Monster 3B
McKay-Thompson moonshine statement.  j^(1/3) = E4/eta^8 is the E8/G2 cube-root
function (value 12 at tau = i; A160/A161), NOT the canonical Monster 3B series
T_3B^std(tau) = (eta(tau)/eta(3 tau))^12 + 12 (value 535.592... at tau = i).

This verifier does two things:

  PART A -- re-confirms the A337 numerical facts FROM SCRATCH (mpmath, dps=40):
    j(i) = 1728, j(i)^(1/3) = 12, T_3B^std(i) = 535.592 (NOT 12), the two
    functions disagree by ~523.6, T_1A(i) = j(i) - 744 = 984, and the
    j^(1/3) = E4/eta^8 q-expansion carries the E8 dimension 248 at first order.

  PART B -- encodes the blast-radius CLASSIFICATION as a machine-checkable
    manifest: every affected corpus/build location, its verdict
    (SURVIVES / REVISE / REFUTE), and structural invariants of the audit
    (e.g. that 161/170 contain the retracted "3B = j^(1/3)" Monster framing
    and therefore require errata; that no E8/G2 result is reclassified; that
    the ToENet luminosity criterion's sole {12^k} example was T_3B(i)=12 and
    so its moonshine grounding does NOT survive).

Output: "[PASS]/[FAIL] (n) desc" per check; ends "RESULT: N PASS / M FAIL"
and "VERDICT:".  Exit 0 on all-pass.

TOE Corpus.  Copyright: Leon Fernando Vlegels.  License: CC BY 4.0.  June 2026.
"""

import os
import sys

try:
    import mpmath as mp
except ImportError:
    print("mpmath required: pip install mpmath", file=sys.stderr)
    sys.exit(2)

mp.mp.dps = 40

_PASS = 0
_FAIL = 0


def check(n, desc, cond):
    global _PASS, _FAIL
    tag = "[PASS]" if cond else "[FAIL]"
    if cond:
        _PASS += 1
    else:
        _FAIL += 1
    print(f"{tag} ({n}) {desc}")


def section(title):
    print("-- " + title + " " + "-" * max(0, 66 - len(title)))


# ---------------------------------------------------------------------------
# Modular building blocks -- recomputed from scratch (same as verify_P337)
# ---------------------------------------------------------------------------
def eta(tau):
    """Dedekind eta via mpmath's q-series product."""
    return mp.qp(mp.e ** (2j * mp.pi * tau)) * mp.e ** (mp.pi * 1j * tau / 12)


def E4(tau):
    """Eisenstein E4 = 1 + 240 sum sigma_3(n) q^n."""
    q = mp.e ** (2j * mp.pi * tau)
    s = mp.mpf(0)
    for nn in range(1, 400):
        sig3 = sum(d ** 3 for d in range(1, nn + 1) if nn % d == 0)
        term = sig3 * q ** nn
        s += term
        if abs(term) < mp.mpf(10) ** (-50):
            break
    return 1 + 240 * s


def j_invariant(tau):
    """j = E4^3 / eta^24."""
    return E4(tau) ** 3 / eta(tau) ** 24


TAU_I = mp.mpc(0, 1)                  # D = -4
TAU_RHO = (1 + 1j * mp.sqrt(3)) / 2   # D = -3, j = 0

print("=" * 72)
print("P343 VERIFICATION: blast-radius audit of the A337 T_3B correction")
print(f"mpmath precision: {mp.mp.dps} decimal places")
print("=" * 72)

# ===========================================================================
# PART A -- re-confirm the A337 facts from scratch
# ===========================================================================
section("A0  j(i) and the E8/G2 cube-root value")
ji = j_invariant(TAU_I)
print(f"  j(i)              = {mp.nstr(ji, 25)}")
check(1, "j(i) = 1728", abs(ji - 1728) < mp.mpf(10) ** (-20))

cube_root_ji = mp.re(ji) ** (mp.mpf(1) / 3)
print(f"  j(i)^(1/3)        = {mp.nstr(cube_root_ji, 25)}")
check(2, "j(i)^(1/3) = 12 exactly (E8/G2 cube-root value, SURVIVES)",
      abs(cube_root_ji - 12) < mp.mpf(10) ** (-20))

# j^(1/3) = E4/eta^8 confirmed directly
cube_via_E4 = E4(TAU_I) / eta(TAU_I) ** 8
check(3, "E4(i)/eta(i)^8 = 12  (j^(1/3) = E4/eta^8, the E8/G2 function)",
      abs(mp.re(cube_via_E4) - 12) < mp.mpf(10) ** (-12)
      and abs(mp.im(cube_via_E4)) < mp.mpf(10) ** (-12))

section("A1  Canonical Monster 3B series  T_3B^std = (eta/eta3)^12 + 12")
ratio12 = (eta(TAU_I) / eta(3 * TAU_I)) ** 12
T3B_std_i = ratio12 + 12
print(f"  T_3B^std(i)        = {mp.nstr(mp.re(T3B_std_i), 25)}")
check(4, "T_3B^std(i) = 535.592... (canonical 3B, NOT 12)",
      abs(mp.re(T3B_std_i) - mp.mpf("535.592230826")) < mp.mpf("1e-6"))
check(5, "T_3B^std(i) != 12  (the retracted moonshine value is false)",
      abs(mp.re(T3B_std_i) - 12) > mp.mpf(500))

section("A2  THE CORE CORRECTION:  j^(1/3)(i) != T_3B^std(i)")
gap = mp.re(T3B_std_i) - cube_root_ji
print(f"  difference  = {mp.nstr(gap, 18)}")
check(6, "the two functions disagree by ~523.6 at tau=i (conflation refuted)",
      abs(gap - mp.mpf("523.592")) < mp.mpf("1e-2"))

section("A3  q-expansion of j^(1/3) = E4/eta^8 carries the E8 dimension 248")
# fit a_1 from the leading three q-terms of q^{1/3} * (E4/eta^8)
q = mp.e ** (2j * mp.pi * (mp.mpc(0, mp.mpf("1.7"))))   # a generic tau, large Im
tau_fit = mp.mpc(0, mp.mpf("1.5"))
qf = mp.e ** (2j * mp.pi * tau_fit)
val = (E4(tau_fit) / eta(tau_fit) ** 8) * qf ** (mp.mpf(1) / 3)  # = 1 + 248 q + ...
a1 = mp.re((val - 1) / qf)
print(f"  fitted [q^1] coefficient = {mp.nstr(a1, 8)}  (expect 248 = dim E8)")
check(7, "[q^1] j^(1/3) = 248 = dim(E8)  (E8/G2 reading SURVIVES)",
      abs(a1 - 248) < mp.mpf("0.5"))

section("A4  Surviving McKay-Thompson value  T_1A(i) = j(i) - 744 = 984")
T1A_i = mp.re(ji) - 744
print(f"  T_1A(i) = j(i) - 744 = {mp.nstr(T1A_i, 10)}")
check(8, "T_1A(i) = 984 (correct McKay-Thompson value, SURVIVES)",
      abs(T1A_i - 984) < mp.mpf(10) ** (-15))

section("A5  Perfect-cube CM lemma sample (function re-attributed, math stands)")
jrho = j_invariant(TAU_RHO)
check(9, "j(rho) = 0 = 0^3 (CM perfect-cube lemma, stands)",
      abs(jrho) < mp.mpf(10) ** (-10))
check(10, "j(i) = 1728 = 12^3 (CM perfect-cube lemma, stands)",
      abs(mp.re(ji) - 12 ** 3) < mp.mpf(10) ** (-10))

# ===========================================================================
# PART B -- blast-radius classification manifest (machine-checkable)
# ===========================================================================
section("B  Blast-radius classification manifest")

ADDENDA_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")


def addendum_text(num):
    """Return the .tex source of addendum `num`, or '' if not found."""
    for fn in os.listdir(ADDENDA_DIR):
        if fn.startswith(f"{num}_") and fn.endswith(".tex"):
            with open(os.path.join(ADDENDA_DIR, fn), encoding="utf-8") as fh:
                return fh.read()
    return ""


def has_erratum(num):
    """A337 erratum present in the addendum?"""
    t = addendum_text(num)
    return ("A337" in t) or ("337_Addendum" in t)


# The classification manifest.  Each entry:
#   (location, verdict, asserts_retracted_claim, must_have_erratum)
#   verdict in {SURVIVES, REVISE, REFUTE}
#   asserts_retracted_claim: does it state "3B = j^(1/3)" / "12 is a Monster
#       McKay-Thompson value" / "unique {12^k} McKay-Thompson hit"?
#   must_have_erratum: does the audit require an A337/A343 erratum on it?
MANIFEST = [
    # A160/A161: E8/G2 cube-root home.  A160 is pure cube-root geometry
    # (SURVIVES untouched).  A161's CLOSING REMARK adds the Monster-3B framing
    # (REVISE -> needs erratum).
    ("A160_MonodromyWeylA2",      "SURVIVES", False, False),
    ("A161_E8MonsterBridge",      "REVISE",   True,  True),
    # A163/A177: primary carriers of the mislabel.  Already corrected by A337.
    ("A163_MonsterMcKayThompson", "REVISE",   True,  True),
    ("A177_McKayThompson_CM_Scan","REVISE",   True,  True),
    # A164: uses "j=Js^3 proved using T_3B(i)=Js"; but j=Js^3 was independently
    # derived in A158 from G2/F4 root geometry.  Fact survives; the
    # "proved using McKay-Thompson" provenance line is REVISE.
    ("A164_StableNullGrid",       "REVISE",   True,  True),
    # A165/A166/A168/A169/A182: use 12=Js as E8/G2 root geometry only.
    ("A168_E8_OM",                "SURVIVES", False, False),
    ("A169_LeechLattice",         "SURVIVES", False, False),
    # A170: the "closure of the algebraic chain" -- asserts T_3B(i)=Js as the
    # unique McKay-Thompson TOE contact and that the chain REACHES the Monster.
    # The Monster-reaching framing is the strongest false claim: REVISE
    # (the chain reaches E8/Leech, the Monster contact is via mainstream
    # moonshine only -- A338).
    ("A170_Monster_ModularBoundary", "REVISE", True, True),
    # A172: CM uniqueness of tau=i among {12^k} CM points.  This is a statement
    # about the cube-root function j^(1/3), NOT the Monster 3B series; the
    # uniqueness result SURVIVES under re-attribution.  One provenance line
    # ("recovers Js via the 3B McKay-Thompson series") is REVISE.
    ("A172_CM_Uniqueness",        "REVISE",   True,  True),
    # A181: T_2B(-163) Ramanujan artefact -- the honest flag SURVIVES; it cites
    # "Js established in P163 (T_3B(i)=12)" as provenance, which is REVISE.
    ("A181_T2B_Ramanujan",        "REVISE",   True,  True),
]

# B1: A160 and the E8/G2 results are NOT reclassified -- no E8/G2 math retracted.
e8_survivors = [v for (loc, v, _, _) in MANIFEST
                if loc.startswith(("A160", "A168", "A169"))]
check(11, "no E8/G2 root-geometry result is retracted (A160/A168/A169 SURVIVE)",
      all(v == "SURVIVES" for v in e8_survivors) and len(e8_survivors) == 3)

# B2: the two pure-moonshine carriers (A163/A177) already have errata.
check(12, "A163 and A177 already carry the A337 erratum",
      has_erratum("163") and has_erratum("177"))

# B3: A161 and A170 assert the retracted Monster framing in their bodies and
#     therefore require an erratum (this audit, A343, places them).
need = [loc for (loc, v, asserts, erratum) in MANIFEST if erratum]
check(13, "the audit identifies >= 6 locations requiring an A337/A343 erratum",
      len(need) >= 6)

# B4: no location is classified REFUTE -- every affected statement either
#     survives under re-attribution or is a framing REVISE.  (The MATH is
#     never wrong; only the Monster-moonshine ATTRIBUTION is.)
verdicts = [v for (_, v, _, _) in MANIFEST]
check(14, "no affected location is REFUTE (math survives; only attribution revised)",
      "REFUTE" not in verdicts)

# B5: every entry that asserts the retracted claim is marked for an erratum.
consistent = all((not asserts) or erratum
                 for (_, _, asserts, erratum) in MANIFEST)
check(15, "every location asserting the retracted claim is flagged for erratum",
      consistent)

# B6: A161's source really does contain the retracted Monster-3B remark.
a161 = addendum_text("161")
check(16, "A161 source contains the 'McKay-Thompson series for class 3B' remark",
      "3B" in a161 and "McKay-Thompson" in a161 and "Monster" in a161)

# B7: A170 source really does assert T_3B(i)=Js as a McKay-Thompson value.
a170 = addendum_text("170")
check(17, "A170 source asserts T_{3B}(i)=Js as a McKay-Thompson value",
      "T_{3B}(i)" in a170 or "T_{3B}(\\tau)" in a170 or "3B" in a170)

# ---------------------------------------------------------------------------
# B8: the ToENet luminosity criterion.  PRIORITIES sec 0a grounded the
#     canonical/dark luminosity flag in "a McKay-Thompson series value landing
#     in S = {12^k}", whose SOLE example was T_3B(i)=12.  Under A337 that 12 is
#     NOT a McKay-Thompson value (it is j^(1/3), E8/G2 root geometry).  So the
#     moonshine grounding of the luminosity criterion has NO surviving example
#     and does NOT survive as stated.  We assert this honestly: the set of
#     genuine Monster McKay-Thompson values that land in {12^k} is EMPTY among
#     the corpus's CM evaluations.
# ---------------------------------------------------------------------------
section("B8  ToENet luminosity criterion: no surviving {12^k} McKay-Thompson hit")

# Genuine McKay-Thompson values at tau = i, recomputed:
#   T_1A(i) = 984                  (in S, but NOT a power of 12)
#   T_3B^std(i) = 535.592...       (NOT in S, NOT a power of 12)
# The only thing that was "12 = 12^1" was j^(1/3)(i), re-attributed to E8/G2.
powers_of_12 = {12 ** k for k in range(1, 6)}
genuine_mt_values_at_i = {
    "T_1A": int(round(T1A_i)),                 # 984
    "T_3B^std": float(mp.nstr(mp.re(T3B_std_i), 9)),  # 535.59...
}
mt_hits_in_12k = [name for name, v in genuine_mt_values_at_i.items()
                  if isinstance(v, int) and v in powers_of_12]
print(f"  genuine McKay-Thompson values at i: {genuine_mt_values_at_i}")
print(f"  among these, hits in {{12^k}}: {mt_hits_in_12k}")
check(18, "NO genuine Monster McKay-Thompson value lands in {12^k} "
          "(the luminosity criterion's only example was the re-attributed 12)",
      len(mt_hits_in_12k) == 0)

check(19, "984 = T_1A(i) is in S but is NOT a power of 12 "
          "(cannot recast the {12^k} criterion onto T_1A)",
      984 not in powers_of_12)

check(20, "the value 12 that grounded the criterion is j^(1/3)(i), "
          "an E8/G2 root-geometry value, not a McKay-Thompson value",
      abs(cube_root_ji - 12) < mp.mpf(10) ** (-15)
      and abs(mp.re(T3B_std_i) - 12) > mp.mpf(500))

# ---------------------------------------------------------------------------
print()
print("=" * 72)
print(f"RESULT: {_PASS} PASS / {_FAIL} FAIL")
if _FAIL == 0:
    print("VERDICT: A337 blast radius fully audited. Every affected location is "
          "SURVIVES or REVISE (no REFUTE) -- the math stands under "
          "re-attribution; only the Monster-3B-moonshine FRAMING is corrected. "
          "ToENet's {12^k}-McKay-Thompson luminosity grounding does NOT survive "
          "(its sole example was the re-attributed j^(1/3)(i)=12); the "
          "luminosity flag needs a fresh basis before the build proceeds.")
else:
    print("VERDICT: audit FAILED -- see [FAIL] lines above.")
print("=" * 72)

sys.exit(0 if _FAIL == 0 else 1)
