#!/usr/bin/env python3
"""verify_P319.py -- Verifier for Addendum 319 (OI-287-1, the boundary S^3
problem directly).

Recomputes from scratch and asserts, by machine:

  S1  The boundary harmonic spectrum is the genuine SO(4) data (sanity vs A314):
      the so(4) = su(2) (+) su(2) Casimir on the (j,j) irrep is 4 j(j+1) = L(L+2)
      (L = 2j), the -Delta_S^3 spectrum (0, 3, 8 for L = 0, 1, 2) with
      multiplicity (L+1)^2 (1, 4, 9). The same su(2) ladder / Casimir A314 used.

  S2  Each boundary formulation gives three DISTINCT families (no A316-style
      degeneracy collapse): B-harm (families = lowest harmonic degrees L=0,1,2)
      and B-lens (families = Z_3 character classes on L(3,1)) each produce three
      distinct diagonal entries.

  S3  Each formulation's normalized diagonal / mu / tau / peak / L2, recomputed
      from scratch, matches the probe. Whether the boundary problem reaches the
      GAP [1.34, 2.0] no radial channel reached, and the HIT/PARTIAL/NULL
      verdict's defining condition, asserted honestly.

The boundary problem OVERSHOOTS: B-lens (canonical, Z_3 character) gives
mu = 3.86, B-harm gives mu = 6.28, both far above the target 1.5 and above the
radial fiber overshoots (2.3-3.14). It does NOT reach the [1.34, 2.0] gap and does
NOT beat the radial-best L2 = 0.399. NULL: the magnitude is in NEITHER the radial
nor the pure-boundary reduction.

Copyright Léon Fernando Vlegels -- CC BY 4.0
"""
import sys
import math

import numpy as np

PI = math.pi
C = (2.0, 3.0, 16.0)
TARGET = [c / C[0] for c in C]                 # (1, 1.5, 8)
SCALAR_CLOSEST_L2 = 0.399
GAP_LO, GAP_HI = 1.34, 2.0
PASS = FAIL = 0


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


# --- su(2) generators + so(4) Casimir (independent rebuild, A314 construction) -
def su2(j):
    dim = int(round(2 * j + 1))
    ms = [j - i for i in range(dim)]
    Jp = np.zeros((dim, dim), dtype=complex)
    Jz = np.zeros((dim, dim), dtype=complex)
    for i, m in enumerate(ms):
        Jz[i, i] = m
        if i - 1 >= 0:
            Jp[i - 1, i] = math.sqrt(j * (j + 1) - m * (m + 1))
    Jm = Jp.conj().T
    return (Jp + Jm) / 2.0, (Jp - Jm) / (2.0j), Jz


def so4_data(L):
    j = L / 2.0
    Lx, Ly, Lz = su2(j)
    d = Lx.shape[0]
    I = np.eye(d, dtype=complex)
    JL = [np.kron(A, I) for A in (Lx, Ly, Lz)]
    JR = [np.kron(I, A) for A in (Lx, Ly, Lz)]
    C2 = np.zeros((d * d, d * d), dtype=complex)
    for i in range(3):
        A = JL[i] + JR[i]
        B = JL[i] - JR[i]
        C2 = C2 + A @ A + B @ B
    ev = np.linalg.eigvalsh((C2 + C2.conj().T) / 2.0).real
    casimir = float(np.mean(ev))
    mult = d * d
    m_weights = list(range(-L, L + 1, 2))
    return casimir, mult, m_weights, (ev.max() - ev.min())


def spec_block(Lmax=2):
    return {L: so4_data(L) for L in range(Lmax + 1)}


def specweight(casimir, mult):
    return casimir if casimir > 1e-9 else float(mult)


def norm_diag(M):
    d = [M[n, n] for n in range(3)]
    return [v / d[0] for v in d]


def l2(ratio):
    return math.sqrt(sum((ratio[i] - TARGET[i]) ** 2 for i in range(3)))


def diag_peaks(M):
    Z = np.zeros_like(M)
    for k in range(3):
        c = M[:, k]
        Z[:, k] = (c - c.mean()) / c.std() if c.std() > 0 else 0.0
    return all(int(np.argmax(Z[:, k])) == k for k in range(3))


def build_harm(spec):
    L_of = [0, 1, 2]
    B = np.zeros((3, 3))
    for n in range(3):
        L = L_of[n]
        cas, mult, _, _ = spec[L]
        w = specweight(cas, mult)
        for k in (1, 2, 3):
            B[n, k - 1] = C[k - 1] * PI ** k * mult / w
    return B


def build_lens(spec, Lmax=2):
    classes = {0: [], 1: [], 2: []}
    for L in range(Lmax + 1):
        cas, mult, ms, _ = spec[L]
        for k in (0, 1, 2):
            cnt = sum(1 for m in ms if (m % 3) == k)
            if cnt > 0:
                classes[k].append((L, cnt))
    B = np.zeros((3, 3))
    for n in range(3):
        k = n
        num = den = 0.0
        for (L, cnt) in classes[k]:
            cas, mult, _, _ = spec[L]
            wL = cas if cas > 1e-9 else 1.0
            num += wL * cnt
            den += cnt
        cw = (num / den) if den > 0 else 1.0
        for j in (1, 2, 3):
            B[n, j - 1] = C[j - 1] * PI ** j * den / cw
    return B, classes


def flat_control():
    B = np.zeros((3, 3))
    for n in range(3):
        for j in (1, 2, 3):
            B[n, j - 1] = C[j - 1] * PI ** j * 4.0 / 3.0
    return B


# ===========================================================================
print("S1  Boundary harmonic spectrum is the genuine SO(4) data (sanity vs A314)")

spec = spec_block(2)

cas_ok = all(abs(spec[L][0] - L * (L + 2)) < 1e-9 for L in (0, 1, 2))
block_deg = all(spec[L][3] < 1e-8 for L in (0, 1, 2))
check(1, "so(4) Casimir 4j(j+1) = L(L+2): casimir = (0, 3, 8) for L=0,1,2, "
      "block-degenerate (the -Delta_S^3 boundary Laplacian spectrum)",
      cas_ok and block_deg)

mult_ok = all(spec[L][1] == (L + 1) ** 2 for L in (0, 1, 2))
check(2, "degree-L harmonic multiplicity (L+1)^2 = (1, 4, 9) for L=0,1,2",
      mult_ok)

# ===========================================================================
print("S2  Each boundary formulation gives three distinct families (no collapse)")

B_harm = build_harm(spec)
B_lens, classes = build_lens(spec)

dh = [B_harm[n, n] for n in range(3)]
harm_distinct = (abs(dh[0] - dh[1]) > 1e-9 and abs(dh[0] - dh[2]) > 1e-9
                 and abs(dh[1] - dh[2]) > 1e-9)
check(3, "B-harm (families = lowest harmonic degrees L=0,1,2) gives three "
      "distinct diagonal entries (no A316 collapse)", harm_distinct)

dl = [B_lens[n, n] for n in range(3)]
lens_distinct = (abs(dl[0] - dl[1]) > 1e-9 and abs(dl[0] - dl[2]) > 1e-9
                 and abs(dl[1] - dl[2]) > 1e-9)
# the lens classes must be genuinely populated and the canonical (Z_3) family
# definition must keep all three classes non-empty (the complex omega^k structure)
classes_populated = all(len(classes[k]) > 0 for k in (0, 1, 2))
check(4, "B-lens (families = Z_3 character classes on L(3,1)) gives three "
      "distinct diagonal entries and all three classes are populated "
      "(the native omega^k structure)", lens_distinct and classes_populated)

# ===========================================================================
print("S3  Diagonals, mu, tau, peak, L2; gap reach; verdict's defining condition")

ratio_h = norm_diag(B_harm)
ratio_l = norm_diag(B_lens)
ctrl = flat_control()
ctrl_peak = diag_peaks(ctrl)

# B-harm: overshoots, mu = 6.28, tau ~ 88.8, no peak
mu_h, tau_h, L2_h = ratio_h[1], ratio_h[2], l2(ratio_h)
peak_h = diag_peaks(B_harm) and not ctrl_peak
check(5, "B-harm diagonal (1, %.2f, %.1f): mu = %.2f (overshoot), tau = %.1f, "
      "L2 = %.2f, no valid peak (%s)"
      % (mu_h, tau_h, mu_h, tau_h, L2_h, peak_h),
      abs(mu_h - 6.2832) < 1e-2 and abs(tau_h - 88.83) < 0.1
      and not peak_h and abs(L2_h - 80.97) < 0.5)

# B-lens (canonical): overshoots, mu = 3.86, tau ~ 64.6, no peak
mu_l, tau_l, L2_l = ratio_l[1], ratio_l[2], l2(ratio_l)
peak_l = diag_peaks(B_lens) and not ctrl_peak
check(6, "B-lens (canonical) diagonal (1, %.2f, %.1f): mu = %.2f (overshoot), "
      "tau = %.1f, L2 = %.2f, no valid peak (%s)"
      % (mu_l, tau_l, mu_l, tau_l, L2_l, peak_l),
      abs(mu_l - 3.8556) < 1e-2 and abs(tau_l - 64.60) < 0.1
      and not peak_l and abs(L2_l - 56.65) < 0.5)

# the GAP: neither formulation reaches [1.34, 2.0]; both overshoot past it
reaches_gap = ((GAP_LO <= mu_h <= GAP_HI) or (GAP_LO <= mu_l <= GAP_HI))
check(7, "the boundary problem does NOT reach the [1.34, 2.0] gap no radial "
      "channel could (B-harm mu = %.2f, B-lens mu = %.2f both above 2.0): "
      "reaches_gap = %s" % (mu_h, mu_l, reaches_gap),
      not reaches_gap)

# the verdict's defining condition: NULL. Canonical does not hit; boundary does
# not reach the gap and does not beat the radial-best L2 = 0.399.
canonical_hits = (all(abs(ratio_l[i] - TARGET[i]) <= 0.20 * TARGET[i]
                      for i in range(3)) and peak_l)
beats_radial = (L2_h < SCALAR_CLOSEST_L2 - 1e-9
                or L2_l < SCALAR_CLOSEST_L2 - 1e-9)
verdict_null = (not canonical_hits) and (not reaches_gap) and (not beats_radial)
nan_found = any(v != v for v in ratio_h + ratio_l)
check(8, "NULL verdict's defining condition holds: canonical (Z_3) map does NOT "
      "hit, boundary does NOT reach the gap, boundary does NOT beat the "
      "radial-best L2 = 0.399; no NaN (magnitude in NEITHER reduction)",
      verdict_null and not nan_found)

print(f"\n{'='*60}\nRESULT: {PASS} PASS / {FAIL} FAIL")
sys.exit(0 if FAIL == 0 else 1)
