#!/usr/bin/env python3
"""verify_P317.py -- Verifier for Addendum 317 (complex Hopf-fibered selection).

Recomputes the keystone complex-realization probe from scratch and asserts the
pre-registered conditions of A317. A316 closed the family-to-mode route in the
REAL radial reduction and named the blocker: the families are the COMPLEX omega^k
cube-root eigenspaces of the layer-cycle, but the real reduction folds omega and
omega^2 together (Re(omega^k) = (1,-1/2,-1/2), so k=1,2 collapse). A317 moves to a
complex realization. On the Hopf fibration S^1 -> S^3 -> S^2 the layer-cycle
psi -> psi + 2pi/3 acts on the fiber-momentum sector e^{i m psi} by omega^m, so
the omega^k eigenspace is { m == k (mod 3) }, lowest rep m=k. The fiber momentum
m enters the radial operator as a genuine m-dependent term (P18 S3.3 fiber
Laplacian, eigenvalue m^2), tested in two corpus-faithful forms:
  F-lap : O_m = -d^2/dr^2 - (3/r)d/dr + V_eff(r) + m^2     (flat additive m^2)
  F-Hopf: O_m = -d^2/dr^2 - (3/r)d/dr + m^2/r^2 + V_eff(r) (cone/Hopf 1/r^2)
Canonical map: family k -> ground state of the m=k sector (k=0,1,2). All in r^3
dr; gen_eigh numpy Cholesky reduction (scipy unavailable).

Finding: the A316 degeneracy IS broken (m=0,1,2 give three genuinely distinct
operators and three distinct entries), the key structural result. But the
canonical map OVERSHOOTS: F-lap mu=2.43, F-Hopf mu=2.29, both far above 1.5 with
no peak, and neither improves on the A316 real-reduction closest (L2=0.399,
mu=1.222). VERDICT NULL: the genuine omega^k phase breaks the degeneracy but does
NOT supply the magnitude; the residual is elsewhere. The verifier encodes this
honest verdict.

  S1  degeneracy broken: three distinct entries, both forms       - checks 1-3
  S2  the canonical map's diagonal/mu/tau/L2/peak, both forms      - checks 4-6
  S3  NULL verdict honest condition (no hit, no improvement) + clean - checks 7-8
"""
import sys
import math

import numpy as np


def gen_eigh(A, Bm):
    L = np.linalg.cholesky(Bm)
    Linv = np.linalg.inv(L)
    Cmat = Linv @ A @ Linv.T
    Cmat = 0.5 * (Cmat + Cmat.T)
    w, y = np.linalg.eigh(Cmat)
    return w, Linv.T @ y


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}")


PI = math.pi
OM = 4 * PI**3 + PI**2 + PI
ES = 13.177
C = (2.0, 3.0, 16.0)
TGT = [c / C[0] for c in C]
N = 1500
CANONICAL_M = [0, 1, 2]
A316_L2 = 0.399
A316_MU = 1.222


def rho_p(x):
    return 48 * PI**3 * x**2 + 6 * PI**2 * x + 2 * PI


def Vpot(x):
    return rho_p(x)**2 / (2 * OM**2) + ES * x**2 * (1 - x)**2


def grid():
    dx = 1.0 / N
    return np.linspace(dx, 1 - dx, N - 1), dx


def radial_matrices(x, dx, V_on_grid, weight):
    n = N - 1
    w_mid = 0.5 * (weight[:-1] + weight[1:])
    w_mid_left0 = max(0.5 * (0.0 + weight[0]), 0.0)
    A = np.zeros((n, n))
    for i in range(n):
        wl = w_mid[i - 1] if i > 0 else w_mid_left0
        wr = w_mid[i] if i + 1 < n else weight[i]
        A[i, i] = (wl + wr) / dx**2
        if i + 1 < n:
            A[i, i + 1] = -w_mid[i] / dx**2
            A[i + 1, i] = -w_mid[i] / dx**2
    A += np.diag(weight * V_on_grid)
    A = 0.5 * (A + A.T)
    return A, np.diag(weight)


def solve_fiber(m, form, n_modes=2):
    x, dx = grid()
    w_arr = x**3
    if form == "F_lap":
        fiber = float(m**2) * np.ones_like(x)
    elif form == "F_Hopf":
        fiber = (float(m**2) / x**2) if m > 0 else np.zeros_like(x)
    else:
        raise ValueError(form)
    A, Wm = radial_matrices(x, dx, Vpot(x) + fiber, w_arr)
    w, v = gen_eigh(A, Wm)
    o = np.argsort(w)
    w = w[o]
    v = v[:, o]
    vv = v[:, :n_modes].copy()
    for k in range(n_modes):
        nrm = math.sqrt(float(np.sum(vv[:, k]**2 * w_arr) * dx))
        vv[:, k] = vv[:, k] / nrm
    return x, dx, w[:n_modes], vv


def overlap_row(col, x, dx, w_arr, lam):
    norm = float(np.sum(col**2 * w_arr) * dx)
    return [float(np.sum(col**2 * C[k - 1] * PI**k * x**k * w_arr) * dx)
            / norm / lam for k in (1, 2, 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 l2(ratio):
    return math.sqrt(sum((ratio[i] - TGT[i])**2 for i in range(3)))


def box_states(x):
    pb = np.column_stack([math.sqrt(2.0) * np.sin((n + 1) * PI * x)
                          for n in range(3)])
    lb = np.array([(n + 1)**2 * PI**2 for n in range(3)])
    return pb, lb


def eval_form(form, pb, lb):
    x, dx = grid()
    w_arr = x**3
    states = np.zeros((N - 1, 3))
    lams = np.zeros(3)
    for k in range(3):
        _, _, w_m, v_m = solve_fiber(CANONICAL_M[k], form, 2)
        states[:, k] = v_m[:, 0]
        lams[k] = w_m[0]
    M = np.array([overlap_row(states[:, n], x, dx, w_arr, lams[n])
                  for n in range(3)])
    Mbox = np.array([overlap_row(pb[:, n], x, dx, w_arr, lb[n])
                     for n in range(3)])
    d = [M[n, n] for n in range(3)]
    ratio = [v / d[0] for v in d]
    peak = diag_peaks(M)
    box_peak = diag_peaks(Mbox)
    valid_peak = peak and not box_peak
    within20 = all(abs(ratio[i] - TGT[i]) <= 0.20 * TGT[i] for i in range(3))
    degen = any(abs(lams[a] - lams[b]) < 1e-6
                and all(abs(M[a, q] - M[b, q]) < 1e-6 for q in range(3))
                for a in range(3) for b in range(a + 1, 3))
    distinct = (abs(d[0] - d[1]) > 1e-6 and abs(d[0] - d[2]) > 1e-6
                and abs(d[1] - d[2]) > 1e-6)
    return {
        "mu": ratio[1], "tau": ratio[2], "ratio": ratio,
        "valid_peak": valid_peak, "within20": within20,
        "hit": within20 and valid_peak, "L2": l2(ratio),
        "lams": [float(v) for v in lams], "degen": degen,
        "distinct": distinct,
    }


# ---- recompute -----------------------------------------------------------
pb, lb = box_states(grid()[0])
R = {f: eval_form(f, pb, lb) for f in ("F_lap", "F_Hopf")}

degeneracy_broken = all(R[f]["distinct"] and not R[f]["degen"]
                        for f in R)
any_hit = any(R[f]["hit"] for f in R)
improves = any(R[f]["L2"] < A316_L2 - 1e-9 for f in R)
moves_mu = any(abs(R[f]["mu"] - 1.5) < abs(A316_MU - 1.5) - 1e-9 for f in R)
closest = min(R, key=lambda f: R[f]["L2"])
nan_found = any(v != v for f in R
                for v in R[f]["ratio"] + R[f]["lams"] + [R[f]["mu"], R[f]["tau"]])

verdict = ("FORCED" if any_hit
           else "NULL" if (not improves and not moves_mu)
           else "STRENGTHENED_PARTIAL")

# the m=0 sector ground state is the pure-radial 4D operator (A316 node-count
# ground): its degree-1 diagonal entry is the normalization base; the m=0
# eigenvalue should match the A316 C_4Dself ground eigenvalue ~23.27.
m0_eig = R["F_lap"]["lams"][0]

# ---- assertions ----------------------------------------------------------
print("S1  the A316 degeneracy is broken: three distinct entries, both forms")
check(1, "the complex realization gives m=0,1,2 as three GENUINELY DISTINCT "
      "operators: F-lap eigenvalues %s differ (m^2 shifts 0,1,4); F-Hopf "
      "eigenvalues %s differ (m^2/r^2). The key structural fact vs A316."
      % ([round(v, 3) for v in R["F_lap"]["lams"]],
         [round(v, 3) for v in R["F_Hopf"]["lams"]]),
      len(set(round(v, 4) for v in R["F_lap"]["lams"])) == 3
      and len(set(round(v, 4) for v in R["F_Hopf"]["lams"])) == 3)
check(2, "A316 DEGENERACY BROKEN: both forms give three distinct diagonal "
      "entries and NO degenerate-selection collapse (F-lap distinct=%s degen=%s; "
      "F-Hopf distinct=%s degen=%s) -- unlike A316 S_Z3 where k=1,2 collapsed"
      % (R["F_lap"]["distinct"], R["F_lap"]["degen"],
         R["F_Hopf"]["distinct"], R["F_Hopf"]["degen"]),
      degeneracy_broken)
check(3, "the m=0 fiber sector reproduces the pure-radial 4D operator (A316 "
      "node-count ground): m=0 ground eigenvalue %.4f ~ 23.27 (C_4Dself "
      "ground); both forms agree at m=0 (F-lap %.4f, F-Hopf %.4f)"
      % (m0_eig, R["F_lap"]["lams"][0], R["F_Hopf"]["lams"][0]),
      abs(m0_eig - 23.27) < 0.1
      and abs(R["F_lap"]["lams"][0] - R["F_Hopf"]["lams"][0]) < 1e-6)

print("S2  the canonical complex map's diagonal / mu / tau / L2 / peak")
check(4, "F-lap canonical map (family k -> ground of m=k, flat +m^2): diagonal "
      "(1, %.4f, %.4f), mu=%.4f, tau=%.4f, L2=%.4f -- OVERSHOOTS far above 1.5, "
      "no valid peak (peak=%s)"
      % (R["F_lap"]["mu"], R["F_lap"]["tau"], R["F_lap"]["mu"],
         R["F_lap"]["tau"], R["F_lap"]["L2"], R["F_lap"]["valid_peak"]),
      abs(R["F_lap"]["mu"] - 2.4274) < 0.01
      and abs(R["F_lap"]["tau"] - 21.0403) < 0.05
      and R["F_lap"]["mu"] > 1.5 and not R["F_lap"]["valid_peak"])
check(5, "F-Hopf canonical map (family k -> ground of m=k, m^2/r^2): diagonal "
      "(1, %.4f, %.4f), mu=%.4f, tau=%.4f, L2=%.4f -- also OVERSHOOTS, no valid "
      "peak (peak=%s)"
      % (R["F_Hopf"]["mu"], R["F_Hopf"]["tau"], R["F_Hopf"]["mu"],
         R["F_Hopf"]["tau"], R["F_Hopf"]["L2"], R["F_Hopf"]["valid_peak"]),
      abs(R["F_Hopf"]["mu"] - 2.2901) < 0.01
      and abs(R["F_Hopf"]["tau"] - 20.7261) < 0.05
      and R["F_Hopf"]["mu"] > 1.5 and not R["F_Hopf"]["valid_peak"])
check(6, "neither fiber form's canonical map HITS: neither lands within 20%% of "
      "(1,1.5,8) and neither restores a valid peak (any_hit=%s); the closest "
      "form is %s (L2=%.4f)"
      % (any_hit, closest, R[closest]["L2"]),
      not any_hit and not R["F_lap"]["hit"] and not R["F_Hopf"]["hit"]
      and not R["F_lap"]["within20"] and not R["F_Hopf"]["within20"])

print("S3  NULL verdict honest condition (no improvement on A316) + clean")
check(7, "VERDICT NULL: the complex realization does NOT improve on the A316 "
      "real-reduction closest (L2=%.3f, mu=%.3f): improves_L2=%s, "
      "moves_mu_toward_1.5=%s -- both fiber forms overshoot mu (2.43, 2.29) and "
      "blow up L2 (~13), so the genuine omega^k phase does NOT supply the "
      "magnitude; OI-287-1 magnitude does NOT close"
      % (A316_L2, A316_MU, improves, moves_mu),
      verdict == "NULL" and not improves and not moves_mu and not any_hit)
check(8, "clean and honest: no NaN; the CANONICAL map (family k -> m=k omega^k "
      "eigenspace, declared before computing) was tested for BOTH corpus-faithful "
      "fiber forms and neither hits -- a genuine NULL, not a fit; the degeneracy "
      "IS broken (the real result) but the magnitude residual is elsewhere "
      "(nan=%s, degeneracy_broken=%s)" % (nan_found, degeneracy_broken),
      (not nan_found) and degeneracy_broken and not any_hit
      and verdict == "NULL")

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