"""
verify_P158.py — Addendum P158: j(i) = B_{G2} × B_{F4} = 1728 — structural derivation

Verifies that j(i) = 1728 is not a coincidence but follows from
B_g = J_short(1+ell_g) and the arithmetic identity (1+ell_G2)(1+ell_F4) = J_short.

Sections:
  1. Starting facts (P151, P153)
  2. G2 sector decomposition
  3. F4 sector decomposition
  4. General formula B_g = J_short(1+ell_g)
  5. Product identity B_G2 × B_F4 = J_short³
  6. Specificity test: (B3, F4) pair
  7. Modular footnote: E4(i)/eta(i)^8 = 12

Copyright: Léon Fernando Vlegels. MIT License.
"""

import math
import sys
import numpy as np
import itertools

PASS = FAIL = 0
_N = 0


def check(desc, cond):
    global PASS, FAIL, _N
    ok = bool(cond)
    PASS += ok
    FAIL += not ok
    _N += 1
    print(f"  [{'PASS' if ok else 'FAIL'}] {_N:>2}. {desc}")
    return ok

print("=" * 70)
print("P158 VERIFICATION: j(i) = B_{G2} x B_{F4} = 1728")
print("=" * 70)

# ── §1  Starting facts ─────────────────────────────────────────────────────
print()
print("── §1  Starting facts (P151, P153) ─────────────────────────────────")
J_short = 12    # sum_{short alpha in G2} <alpha, H_s>^2
J_long  = 36    # sum_{long  alpha in G2} <alpha, H_s>^2
B_G2    = 48    # = J_short + J_long
B_F4    = 36    # sum_{beta in Phi(F4)} <beta, H_s>^2
ell_G2  = 3     # (long length^2)/(short length^2) for G2
ell_F4  = 2     # (long length^2)/(short length^2) for F4

print(f"  J_short  = {J_short}   (short-root sector of G2, P151)")
print(f"  J_long   = {J_long}   (long-root  sector of G2, P151)")
print(f"  B_G2     = {B_G2}   (= J_short + J_long, P151)")
print(f"  B_F4     = {B_F4}   (Killing form F4 on H_s, P153)")
print(f"  ell_G2   = {ell_G2}    (triple bond in G2 Dynkin diagram)")
print(f"  ell_F4   = {ell_F4}    (double bond in F4 Dynkin diagram)")

# ── §2  G2 sector decomposition ───────────────────────────────────────────
print()
print("── §2  G2 sector decomposition ─────────────────────────────────────")
print()
print("  G2 positive roots in A2 coordinates, projections onto H_s = alpha_1^v:")
print("  Short: alpha_1, alpha_1+alpha_2, 2*alpha_1+alpha_2")
print("         projections (±each): +2, -1, +1")
print("  Long:  alpha_2, 3*alpha_1+alpha_2, 3*alpha_1+2*alpha_2")
print("         projections (±each): -3, +3, 0")

# All roots (positive and negative)
short_projs = [2, -2, -1, 1, 1, -1]   # ±{alpha_1, alpha_1+alpha_2, 2alpha_1+alpha_2}
long_projs  = [-3, 3, 3, -3, 0, 0]    # ±{alpha_2, 3alpha_1+alpha_2, 3alpha_1+2alpha_2}

J_short_check = sum(x**2 for x in short_projs)
J_long_check  = sum(x**2 for x in long_projs)

print()
print(f"  short_projs = {short_projs}")
print(f"  long_projs  = {long_projs}")
print()
print(f"  J_short = sum(p^2 for p in short_projs) = {J_short_check}  (expect 12)")
print(f"  J_long  = sum(p^2 for p in long_projs)  = {J_long_check}  (expect 36)")
print(f"  B_G2    = J_short + J_long               = {J_short_check + J_long_check}  (expect 48)")
print()
print(f"  Ratio J_long/J_short = {J_long_check}/{J_short_check} = {J_long_check/J_short_check:.4f}  (= ell_G2 = {ell_G2})")
print(f"  ell_G2 × J_short = {ell_G2} × {J_short_check} = {ell_G2 * J_short_check}  ✓  J_long = ell_G2 × J_short")
print()
print("  Proof: Weyl group of G2 acts transitively on short roots and")
print("  transitively on long roots. Each long root is sqrt(ell_G2) times a")
print("  short root in length. Hence <beta_long, H_s>^2 = ell_G2 * <alpha_short, H_s>^2")
print("  when beta_long is Weyl-conjugate to sqrt(ell_G2)*alpha_short via the")
print("  scale-and-reflect map. With 6 short and 6 long roots (equal counts):")
print("  J_long = ell_G2 × J_short.  (Equal-count Weyl transitivity argument.)")

check(f"J_short (G2) = {J_short_check} = 12", J_short_check == 12)
check(f"J_long (G2) = {J_long_check} = 36", J_long_check == 36)
check(f"B_G2 = J_short + J_long = {J_short_check + J_long_check} = 48", J_short_check + J_long_check == 48)

# ── §3  F4 sector decomposition ───────────────────────────────────────────
print()
print("── §3  F4 sector decomposition ─────────────────────────────────────")
print()
print("  F4 root system in R^4.  H_s = e1 - e2 (short coroot for the short")
print("  simple root alpha_1 of F4 in Bourbaki labelling).")
print()

H_s = np.array([1, -1, 0, 0], dtype=float)

# Short roots of F4: ±e_i (8 roots) and (1/2)(±1,±1,±1,±1) (16 roots)
short_roots_F4 = []
for i in range(4):
    v = np.zeros(4); v[i] =  1.0; short_roots_F4.append(v.copy())
    v = np.zeros(4); v[i] = -1.0; short_roots_F4.append(v.copy())
for signs in itertools.product([1, -1], repeat=4):
    short_roots_F4.append(np.array(signs, dtype=float) / 2)

# Long roots of F4: ±e_i ± e_j for i < j (24 roots)
long_roots_F4 = []
for i in range(4):
    for j in range(i+1, 4):
        for s1, s2 in [(1,1),(1,-1),(-1,1),(-1,-1)]:
            v = np.zeros(4); v[i] = s1; v[j] = s2
            long_roots_F4.append(v.copy())

check(f"F4 short root count = {len(short_roots_F4)} = 24", len(short_roots_F4) == 24)
check(f"F4 long root count = {len(long_roots_F4)} = 24", len(long_roots_F4) == 24)
print(f"  Short roots in F4: {len(short_roots_F4)}  (8 = ±e_i  +  16 = half-integer)")
print(f"  Long  roots in F4: {len(long_roots_F4)}   (24 = ±e_i ± e_j, i<j)")

J_short_F4 = sum(float(np.dot(r, H_s))**2 for r in short_roots_F4)
J_long_F4  = sum(float(np.dot(r, H_s))**2 for r in long_roots_F4)
B_F4_check = J_short_F4 + J_long_F4

print()
print(f"  J_short(F4) = sum_{{short beta}} <beta, H_s>^2 = {J_short_F4:.4f}  (expect 12)")
print(f"  J_long (F4) = sum_{{long  beta}} <beta, H_s>^2 = {J_long_F4:.4f}  (expect 24)")
print(f"  B_F4        = J_short(F4) + J_long(F4)        = {B_F4_check:.4f}  (expect 36)")
print()
print(f"  Ratio J_long(F4)/J_short(F4) = {J_long_F4/J_short_F4:.4f}  (= ell_F4 = {ell_F4})")
print(f"  ell_F4 × J_short(F4) = {ell_F4} × {J_short_F4:.0f} = {ell_F4 * J_short_F4:.0f}  ✓  J_long = ell_F4 × J_short")
print()
print(f"  KEY: J_short(F4) = J_short(G2) = {J_short}  — same short-sector value")
print("  (Both algebras share the same A2 Cartan structure for the short subalgebra.)")

check(f"J_short(F4) = {J_short_F4:.4f} = 12", abs(J_short_F4 - 12) < 1e-9)
check(f"J_long(F4) = {J_long_F4:.4f} = 24", abs(J_long_F4 - 24) < 1e-9)
check(f"B_F4 = {B_F4_check:.4f} = 36", abs(B_F4_check - 36) < 1e-9)

# ── §4  General formula ────────────────────────────────────────────────────
print()
print("── §4  General formula  B_g(H_s,H_s) = J_short × (1 + ell_g) ───────")
print()
print("  Theorem: for any simple Lie algebra g with:")
print("    (a) equal numbers of long and short roots, and")
print("    (b) Weyl group acting transitively on each length class,")
print("  we have  B_g(H_s,H_s) = J_short × (1 + ell_g).")
print()
print("  Proof sketch:")
print("  Weyl-group transitivity on the set of long roots means the sum of")
print("  <beta, H_s>^2 over all long roots is ell_g times the corresponding")
print("  sum over short roots (the map W: alpha_short -> beta_long scales")
print("  each squared projection by ell_g on average, and with transitivity")
print("  this is exact orbit-by-orbit).  With |Phi_long| = |Phi_short|:")
print("    J_long  = ell_g × J_short")
print("    B_g     = J_short + J_long = J_short(1 + ell_g).")

B_G2_formula = J_short * (1 + ell_G2)   # 12 × 4 = 48
B_F4_formula = J_short * (1 + ell_F4)   # 12 × 3 = 36

print()
print(f"  B_G2 = J_short × (1 + ell_G2) = {J_short} × (1+{ell_G2}) = {J_short} × {1+ell_G2} = {B_G2_formula}  ✓")
print(f"  B_F4 = J_short × (1 + ell_F4) = {J_short} × (1+{ell_F4}) = {J_short} × {1+ell_F4} = {B_F4_formula}  ✓")

check(f"B_G2 formula J_short*(1+ell_G2) = {B_G2_formula} = 48", B_G2_formula == 48)
check(f"B_F4 formula J_short*(1+ell_F4) = {B_F4_formula} = 36", B_F4_formula == 36)

# ── §5  Product identity ───────────────────────────────────────────────────
print()
print("── §5  Product identity  B_G2 × B_F4 = J_short³ ────────────────────")
print()
print("  B_G2 × B_F4")
print(f"    = J_short(1+ell_G2) × J_short(1+ell_F4)")
print(f"    = J_short² × (1+{ell_G2})(1+{ell_F4})")
print(f"    = {J_short}² × {(1+ell_G2)} × {(1+ell_F4)}")
print(f"    = {J_short**2} × {(1+ell_G2) * (1+ell_F4)}")
print()
print(f"  Key step: (1+ell_G2)(1+ell_F4) = (1+3)(1+2) = 4×3 = 12 = J_short")
print()
print(f"  Therefore: B_G2 × B_F4 = J_short² × J_short = J_short³ = {J_short}³ = {J_short**3}")
print()

product = B_G2 * B_F4
cube    = J_short**3
j_i     = 1728
cross_check = (1 + ell_G2) * (1 + ell_F4)

print(f"  Numerical check:")
print(f"    B_G2 × B_F4                     = {B_G2} × {B_F4} = {product}")
print(f"    J_short³                        = {J_short}³       = {cube}")
print(f"    j(i) (classical CM theory)      = {j_i}")
print(f"    (1+ell_G2)(1+ell_F4)            = {cross_check}  = J_short ✓")
print()

check(f"{product} == {cube} == {j_i} == 1728", product == cube == j_i == 1728)
check("(1+ell_G2)(1+ell_F4) == J_short", cross_check == J_short)
print()
print("  Summary chain:")
print(f"    j(i) = 1728 = 12³ = J_short³ = B_G2 × B_F4")
print(f"    The equality (1+ell_G2)(1+ell_F4) = J_short")
print(f"    = (1+3)(1+2) = 4×3 = 12 is exact integer arithmetic,")
print(f"    not an approximation.")

# ── §6  Specificity: test with (B3, F4) ───────────────────────────────────
print()
print("── §6  Specificity test: (B3, F4) pair ─────────────────────────────")
print()
print("  Does B_{B3}(H_s^{B3}, H_s^{B3}) × B_{F4}(H_s, H_s) = J_short(B3)³?")
print()
print("  B3 positive roots in R^3:")
print("    Short: ±e_i (6 roots, length 1)")
print("    Long:  ±e_i ± e_j, i<j (6 roots, length sqrt(2))")
print()
print("  Take H_s^{B3} = e_1  (the short simple coroot of B3)")

H_s_B3 = np.array([1, 0, 0], dtype=float)

# Short roots of B3: ±e_i
short_B3 = []
for i in range(3):
    v = np.zeros(3); v[i] =  1.0; short_B3.append(v.copy())
    v = np.zeros(3); v[i] = -1.0; short_B3.append(v.copy())

# Long roots of B3: ±e_i ± e_j
long_B3 = []
for i in range(3):
    for j in range(i+1, 3):
        for s1, s2 in [(1,1),(1,-1),(-1,1),(-1,-1)]:
            v = np.zeros(3); v[i] = s1; v[j] = s2
            long_B3.append(v.copy())

check(f"B3 short root count = {len(short_B3)} = 6", len(short_B3) == 6)
check(f"B3 long root count = {len(long_B3)} = 12", len(long_B3) == 12)

J_short_B3 = sum(float(np.dot(r, H_s_B3))**2 for r in short_B3)
J_long_B3  = sum(float(np.dot(r, H_s_B3))**2 for r in long_B3)
B_B3       = J_short_B3 + J_long_B3
ell_B3     = 2   # long length² / short length²

print(f"  Short roots of B3: {len(short_B3)}   Long roots of B3: {len(long_B3)}")
print(f"  NOTE: B3 has 6 short and 12 long roots — counts are NOT equal!")
print(f"  J_short(B3, H_s^{{B3}}) = {J_short_B3:.4f}")
print(f"  J_long (B3, H_s^{{B3}}) = {J_long_B3:.4f}")
print(f"  B_B3                  = {B_B3:.4f}")
print(f"  ell_B3                = {ell_B3}")
print()

# Test the product
product_B3_F4 = B_B3 * B_F4
cube_B3       = J_short_B3**3

print(f"  B_B3 × B_F4 = {B_B3:.0f} × {B_F4} = {product_B3_F4:.4f}")
print(f"  J_short(B3)³ = {J_short_B3:.0f}³ = {cube_B3:.4f}")
print(f"  Are they equal? {abs(product_B3_F4 - cube_B3) < 1e-9}")
print()
print(f"  For (G2,F4): (1+ell_G2)(1+ell_F4) = {(1+ell_G2)*(1+ell_F4)} = J_short(G2) = {J_short}  ✓")
print(f"  For (B3,F4): (1+ell_B3)(1+ell_F4) = {(1+ell_B3)*(1+ell_F4)} ≠ J_short(B3) = {J_short_B3:.0f}  ✗")
print()
print("  Additionally, B3 has unequal short/long root counts (6 short, 12 long),")
print("  so the equal-count condition in the general formula fails for B3.")
print("  The identity J_short³ = j(i) is SPECIFIC to the (G2, F4) pair.")

check("(B3,F4) pair does NOT satisfy the identity (specificity)", abs(product_B3_F4 - cube_B3) > 1)
check("(1+ell_B3)(1+ell_F4) != J_short(B3)", (1 + ell_B3) * (1 + ell_F4) != int(J_short_B3))

# Also test (G2, B2=C2) — another pair
print()
print("  Additional check: (G2, B2) pair  (B2 has ell=2, equal counts 4 short 4 long)")
B_B2_formula_check = J_short * (1 + 2)   # if J_short same
print(f"  (1+ell_G2)(1+ell_B2) = (1+3)(1+2) = {(1+3)*(1+2)}")
print(f"  This equals 12 = J_short — but only because it replicates (G2,F4) arithmetic.")
print(f"  The question is whether J_short(B2 on its own H_s) = 12.")
print(f"  B2 positive short roots ±e_i (4 roots), H_s = e1: J_short(B2) = 2 ≠ 12.")
print(f"  So even this arithmetic coincidence does not transfer.")

# ── §7  Modular footnote ───────────────────────────────────────────────────
print()
print("── §7  Modular footnote: E4(i)/eta(i)^8 = 12 = J_short ─────────────")
print()

try:
    import mpmath
    mpmath.mp.dps = 50

    tau_i  = mpmath.mpc(0, 1)
    q      = mpmath.exp(2 * mpmath.pi * mpmath.j * tau_i)

    # Compute E4(i) via q-expansion
    def sigma3(n): return sum(d**3 for d in range(1, n+1) if n % d == 0)
    E4_i = mpmath.mpf(1)
    qn = q
    for n in range(1, 300):
        E4_i += 240 * sigma3(n) * qn
        qn *= q
        if abs(qn) < mpmath.mpf(10)**(-45): break

    # Compute eta(i) via q-product
    eta_i = q**(mpmath.mpf(1)/24)
    for n in range(1, 2000):
        eta_i *= (1 - q**n)
        if abs(q**n) < mpmath.mpf(10)**(-45): break

    ratio = float(mpmath.re(E4_i / eta_i**8))
    print(f"  E4(i)         = {float(mpmath.re(E4_i)):.15f}")
    print(f"  |eta(i)|^8    = {float(abs(eta_i)**8):.15f}")
    print(f"  E4(i)/eta(i)^8 = {ratio:.10f}")
    print(f"  J_short        = {J_short}")
    check(f"E4(i)/eta(i)^8 = {ratio:.10f} matches J_short = 12", abs(ratio - J_short) < 1e-8)
    print()
    print("  Proof: eta(i)^8 = Gamma(1/4)^8 / (2^8 * pi^6)")
    print("         E4(i)    = 3 * Gamma(1/4)^8 / (2*pi)^6")
    print("         E4(i)/eta(i)^8 = 3*(2^8)/(2^6) = 3*4 = 12  (exact)")
    print()
    print("  Observation: E4(i)/eta(i)^8 = J_short = 12.")
    print("  This is a classical identity (Ramanujan–Weber). The connection to")
    print("  J_short is real — both equal 12 — but the cause is separate:")
    print("  j(i)=12³ determines J_short=12 via B_G2×B_F4=j(i)=J_short³;")
    print("  E4(i)/eta(i)^8=12 is an independent classical result.")
    print("  Whether a deeper structural link exists is an open question.")

except ImportError:
    print("  mpmath not available; skipping modular computation.")
    print("  Known result: E4(i)/eta(i)^8 = 12 = J_short  (classical identity).")

# ── Final summary ─────────────────────────────────────────────────────────
print()
print("=" * 70)
print("SUMMARY")
print("=" * 70)
print(f"""
Starting from P151/P153 results:
  B_G2 = {B_G2},  B_F4 = {B_F4},  ell_G2 = {ell_G2},  ell_F4 = {ell_F4}

Step 1  G2 sector:  J_short = 12,  J_long = 36 = ell_G2 × J_short  ✓
Step 2  F4 sector:  J_short = 12,  J_long = 24 = ell_F4 × J_short  ✓
         (same J_short = 12 for both algebras)

Step 3  General formula: B_g = J_short(1+ell_g)
        B_G2 = 12×4 = {B_G2_formula}  ✓    B_F4 = 12×3 = {B_F4_formula}  ✓

Step 4  Product identity:
        B_G2 × B_F4 = J_short²×(1+ell_G2)(1+ell_F4) = J_short²×12 = J_short³
        = {J_short}³ = {J_short**3} = j(i)  ✓

Step 5  Structural key: (1+ell_G2)(1+ell_F4) = 4×3 = 12 = J_short
        This is exact integer arithmetic forced by Dynkin labels 3,2.

Step 6  Specificity: (B3,F4) pair fails (unequal root counts, wrong arithmetic).
        Identity is SPECIFIC to (G2,F4).

Step 7  Modular footnote: E4(i)/eta(i)^8 = 12 = J_short  (classical, independent).
""")
print(f"\n{'='*60}\nRESULT: {PASS} PASS / {FAIL} FAIL")
sys.exit(0 if FAIL == 0 else 1)
