#!/usr/bin/env python3
"""Distributed classical spectral fabric for the E47 operator D = L (x) I + I (x) B   (B = K^2).

Hubs / backlinks:
  E47-Kartekeya hub   https://github.com/nicholaskouns-create/E47-Kartekeya
  Public App Index    https://gem-sunny-beacon-mountain.grok.me/
  Instruments         https://nicholaskouns-create.github.io/instruments/
  E47 Identity        https://nicholaskouns-create.github.io/e47-identity/
Operator source (verified byte-identical, md5 4bf6e4fc07385ee84e7ef75fcfe6a1ea):
  E47-Kartekeya@e9be2dee website/interfaces/fcc-e47-spatial-lift/fcc_e47_validation.py
  (L line 17, B = K^2 line 39, D = sparse.kronsum(B, L) line 65, spectrum lines 46-62, 68)
Shared conventions: /workspace/shared/z5cube (cross-checked at run time when present).

Fabric layout
  * Row fabric : N_NODES worker processes; node r owns a contiguous row block of D_sym (CSR) and
                 computes y[r0:r1] = D_sym[r0:r1, :] @ x on a shared-memory vector (distributed matvec).
                 Used for independent residual verification ||D v - lambda v|| of every eigenpair and
                 for global trace / Frobenius certificates.
  * Slice fabric: each spectrum slice [lo, hi] is a task on its own worker: shift-invert Lanczos
                 (ARPACK eigsh, sigma = slice centre, local sparse LU of D_sym - sigma I).
Each slice is compared with the analytic spectrum {lambda_FCC + b}: count/multiplicities, max |error|,
residuals, completeness (k-th nearest Ritz value lies outside the slice), PASS/FAIL.

Usage: python3 certify_spectral_fabric.py [--nodes 4] [--out machine_certificates.jsonl]
"""
import os
os.environ.setdefault("OMP_NUM_THREADS", "1"); os.environ.setdefault("OPENBLAS_NUM_THREADS", "1")
import argparse, hashlib, json, os, platform, subprocess, sys, time
from datetime import datetime, timezone
from multiprocessing import Pool, get_context, shared_memory

import numpy as np
import scipy
from scipy.sparse.linalg import eigsh, splu, LinearOperator
from scipy import sparse

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import e47_operator as E

TOL_REL = 1e-10       # |lambda_num - lambda_exact| <= TOL_REL * max(1, |lambda|)
RES_REL = 1e-12       # ||D v - lambda v|| <= RES_REL * ||D||_2  (backward-stable level; by Weyl, a symmetric
                      # residual r puts a true eigenvalue within ||r|| of the Ritz value)
NORM_D = 186624 + (25 + 3 * 5 ** 0.5) / 2   # ||D_sym||_2 = max b + max lambda_FCC (also certified below)
MC_CODE = "MC-E47-SPECTRAL-FABRIC-" + time.strftime("%Y%m%d") + "-001"

SLICES = [  # (name, lo, hi, purpose)
    ("E47-kernel",        -0.5,      0.5,      "ker D = E47 (x) constant mode, mult 47"),
    ("E47-gap",            4.0,      4.3,      "predicted gap (15-3sqrt5)/2, mult 8*47 = 376"),
    ("B-floor-11664",  11663.5,  11664.5,      "squared E47 gap 11664 (c=12), mult 28"),
    ("B-12544",        12543.5,  12544.5,      "c=2 band floor, mult 9"),
    ("singlet-FCC",    32399.5,  32416.0,      "c=0 singlet x full FCC spectrum, 125 levels"),
    ("B-top-186624",  186623.5, 186624.5,      "c=42 band floor (squared max), mult 13"),
]

# ---------------- row fabric (distributed matvec) ----------------
_G = {}

def _row_init(lo, hi, shm_x, shm_y, n):
    D = E.build_D(symmetric=True)
    _G.update(block=D[lo:hi], lo=lo, hi=hi,
              x=shared_memory.SharedMemory(name=shm_x), y=shared_memory.SharedMemory(name=shm_y), n=n)

def _row_matvec(_):
    x = np.ndarray((_G["n"],), dtype=np.float64, buffer=_G["x"].buf)
    y = np.ndarray((_G["n"],), dtype=np.float64, buffer=_G["y"].buf)
    y[_G["lo"]:_G["hi"]] = _G["block"] @ x
    return _G["lo"], _G["hi"], int(_G["block"].nnz)


class RowFabric:
    def __init__(self, n, nodes):
        self.n = n
        bounds = np.linspace(0, n, nodes + 1).astype(int)
        self.layout = [(int(bounds[i]), int(bounds[i + 1])) for i in range(nodes)]
        self.sx = shared_memory.SharedMemory(create=True, size=n * 8)
        self.sy = shared_memory.SharedMemory(create=True, size=n * 8)
        self.x = np.ndarray((n,), np.float64, buffer=self.sx.buf)
        self.y = np.ndarray((n,), np.float64, buffer=self.sy.buf)
        ctx = get_context("fork")
        # one dedicated single-process pool per node, so node r always owns row block r
        self.pools = [ctx.Pool(1, initializer=_row_init, initargs=(lo, hi, self.sx.name, self.sy.name, n))
                      for lo, hi in self.layout]
        self.block_nnz = [p.apply(_row_matvec, (0,))[2] for p in self.pools]

    def matvec(self, v):
        self.x[:] = v
        for r in [p.apply_async(_row_matvec, (0,)) for p in self.pools]:
            r.get()
        return self.y.copy()

    def close(self):
        for p in self.pools:
            p.close(); p.join()
        for s in (self.sx, self.sy):
            s.close(); s.unlink()


# ---------------- slice fabric (shift-invert Lanczos per slice) ----------------
def solve_slice(args):
    name, lo, hi, k = args
    t0 = time.time()
    D = E.build_D(symmetric=True).tocsc()
    n = D.shape[0]
    sigma = 0.5 * (lo + hi) + 1e-3 * (hi - lo)  # small offset avoids sitting exactly on a level
    lu = splu((D - sigma * sparse.identity(n, format="csc")).tocsc())
    OPinv = LinearOperator((n, n), matvec=lu.solve, dtype=np.float64)
    vals, vecs = eigsh(D, k=k, sigma=sigma, which="LM", OPinv=OPinv, tol=1e-13,
                       ncv=min(n - 1, max(2 * k + 20, 60)), v0=np.random.default_rng(47).standard_normal(n))
    order = np.argsort(vals)
    return name, sigma, vals[order], vecs[:, order], time.time() - t0


def match(found, exact_rows):
    exact = np.repeat([v for v, m, _ in exact_rows], [m for v, m, _ in exact_rows]) if exact_rows else np.array([])
    if len(found) != len(exact):
        return False, float("inf"), exact
    err = np.abs(np.sort(found) - exact)
    return True, float(err.max()) if len(err) else 0.0, exact


def z5cube_crosscheck():
    """Cross-check against the shared /workspace/shared/z5cube module (different internal basis: m = 2 - x,
    orthonormal; ours: integer ladder basis k = m + 2, symmetrised by the binomial metric)."""
    sys.path.insert(0, "/workspace/shared/z5cube")
    try:
        import z5cube as z
    except Exception as exc:  # module optional
        return {"available": False, "error": repr(exc)}
    out = {"available": True, "version": getattr(z, "__version__", "?")}
    out["GAP_D"] = float(z.GAP_D); out["GAP_D_abs_err_vs_exact"] = abs(float(z.GAP_D) - E.E47_GAP)
    out["fcc_laplacian_equal"] = bool(np.array_equal(np.asarray(z.fcc_laplacian()).round(12), E.fcc_laplacian()))
    zs = [(round(v, 12), int(p), int(q), int(m)) for v, p, q, m in z.fcc_spectrum_exact()]
    out["fcc_spectrum_exact_equal"] = zs == [(round(v, 12), p, q, m) for v, p, q, m in E.fcc_levels_exact()]
    K = np.asarray(z.selector_K()); kb = np.sort(np.linalg.eigvalsh(K @ K))
    bx = np.repeat([v for v, m in E.penalty_levels()], [m for v, m in E.penalty_levels()]).astype(float)
    out["K2_spectrum_max_err"] = float(np.max(np.abs(kb - bx)))
    P = np.asarray(z.P47()); out["P47_rank"] = int(round(np.trace(P)))
    # apply_D on u0 (x) E47 gives 0, on (gap character) (x) E47 gives gamma
    Q = np.asarray(z.E47_basis())
    u0 = np.ones(125) / np.sqrt(125)
    X = np.asarray(E.SITES); chi = np.cos(2 * np.pi * X[:, 0] / 5); chi /= np.linalg.norm(chi)
    F0 = np.outer(u0, Q[:, 0]); F1 = np.outer(chi, Q[:, 0])
    out["apply_D_kernel_residual"] = float(np.linalg.norm(np.asarray(z.apply_D(F0))))
    out["apply_D_gap_rayleigh_err"] = abs(float(np.sum(F1 * np.asarray(z.apply_D(F1)).real)) - E.E47_GAP)
    out["passed"] = bool(out["GAP_D_abs_err_vs_exact"] <= 1e-12 and out["fcc_laplacian_equal"]
                         and out["fcc_spectrum_exact_equal"] and out["K2_spectrum_max_err"] <= 1e-6
                         and out["P47_rank"] == 47 and out["apply_D_kernel_residual"] <= 1e-10
                         and out["apply_D_gap_rayleigh_err"] <= 1e-10)
    return out


def code_hash():
    h = hashlib.sha256()
    for f in ("certify_spectral_fabric.py", "e47_operator.py"):
        h.update(open(os.path.join(os.path.dirname(os.path.abspath(__file__)), f), "rb").read())
    return h.hexdigest()


def operator_hash(D):
    h = hashlib.sha256()
    for a in (D.indptr, D.indices, D.data):
        h.update(np.ascontiguousarray(a).tobytes())
    return h.hexdigest()


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--nodes", type=int, default=4)
    ap.add_argument("--out", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "machine_certificates.jsonl"))
    args = ap.parse_args()

    D = E.build_D(); Ds = E.build_D(symmetric=True)
    n = D.shape[0]
    s = np.tile(E.symmetrizer(), E.N)  # I (x) S on the flat index 125*site + internal
    spectrum = E.analytic_spectrum()
    assert sum(m for _, m, _ in spectrum) == n

    fabric = RowFabric(n, args.nodes)
    # distributed-matvec sanity: matches serial on a random vector
    xr = np.random.default_rng(0).standard_normal(n)
    matvec_err = float(np.abs(fabric.matvec(xr) - Ds @ xr).max())
    # global certificates (exact identities of the full spectrum)
    trace_D = float(D.diagonal().sum()); trace_exact = sum(v * m for v, m, _ in spectrum)
    frob2 = float((Ds.multiply(Ds)).sum()); frob2_exact = sum(v * v * m for v, m, _ in spectrum)

    t1 = time.time()
    structure = E.kron_block_certificate()
    structure["seconds"] = round(time.time() - t1, 2)
    structure_pass = bool(structure["kernel_dim"] == 47 and structure["gap_abs_err"] <= 1e-10
                          and structure["gap_multiplicity"] == 376 and structure["full_spectrum_max_rel_err"] <= 1e-12
                          and all(x["rel_err"] <= 1e-10 for x in structure["semigroup"]))

    z5 = z5cube_crosscheck()

    tasks = []
    for name, lo, hi, _ in SLICES:
        cnt = sum(m for _, m, _ in E.analytic_in(lo, hi))
        tasks.append((name, lo, hi, cnt + 12))
    t0 = time.time()
    with get_context("fork").Pool(min(len(tasks), os.cpu_count() or 1)) as pool:
        solved = {r[0]: r[1:] for r in pool.map(solve_slice, tasks)}
    wall = time.time() - t0

    common = dict(
        operator="E47 D = L (x) I125 + I125 (x) B  (L: FCC Laplacian on Z5^3; B = K^2, K=(C-6I)(C-30I))",
        operator_source="nicholaskouns-create/E47-Kartekeya website/interfaces/fcc-e47-spatial-lift/fcc_e47_validation.py @ e9be2deefb3e",
        operator_sha256=operator_hash(D), operator_sym_sha256=operator_hash(Ds),
        shape=[n, n], nnz=int(D.nnz),
        partition={"scheme": "contiguous row blocks of D_sym, one process per node", "nodes": args.nodes,
                   "row_blocks": fabric.layout, "block_nnz": fabric.block_nnz},
        distributed_matvec_max_err=matvec_err,
        global_checks={"trace": trace_D, "trace_exact": trace_exact,
                       "frobenius2_rel_err": abs(frob2 - frob2_exact) / frob2_exact},
        structure_certificate=dict(structure, passed=structure_pass,
                                   method="dense eigh of B_sym -> D_sym = (+)_j (L + b_j I); dense eigvalsh per block; "
                                          "Z5^3 character eigenvectors of L; semigroup via dense expm per block "
                                          "(orthonormal/symmetrised frame)"),
        z5cube_crosscheck=z5,
        code_sha256=code_hash(),
        env={"python": platform.python_version(), "numpy": np.__version__, "scipy": scipy.__version__,
             "host": platform.node(), "method": "ARPACK shift-invert Lanczos (splu), residuals via row fabric"},
    )
    records = []
    for name, lo, hi, purpose in SLICES:
        sigma, vals, vecs, secs = solved[name]
        inside = (vals >= lo) & (vals <= hi)
        exact_rows = E.analytic_in(lo, hi)
        count_ok, max_err, exact = match(vals[inside], exact_rows)
        tol = TOL_REL * max(1.0, abs(hi))
        # residuals through the distributed matvec, symmetric and original (non-symmetric) D
        res_sym, res_orig = [], []
        for j in np.flatnonzero(inside):
            v = vecs[:, j]
            res_sym.append(float(np.linalg.norm(fabric.matvec(v) - vals[j] * v)))
            w = v / s; w /= np.linalg.norm(w)
            res_orig.append(float(np.linalg.norm(D @ w - vals[j] * w)))
        # completeness: farthest returned Ritz value is outside the slice on the far side
        reach = float(np.max(np.abs(vals - sigma)))
        complete = reach > max(abs(hi - sigma), abs(lo - sigma))
        # out-of-slice Ritz values must also be analytic eigenvalues
        allv = np.array([v for v, _, _ in spectrum])
        # (relative to each value's own magnitude, same rule as TOL_REL; informational neighbours)
        outside_err = float(max((np.min(np.abs(allv - x)) / max(1.0, abs(x)) for x in vals[~inside]), default=0.0))
        mult = [{"exact": lab, "value": v, "multiplicity": m,
                 "found": int(np.sum(np.abs(vals[inside] - v) <= max(1e-6, 1e-9 * abs(v))))} for v, m, lab in exact_rows]
        rmax = max(res_sym, default=0.0)
        passed = bool(count_ok and complete and max_err <= tol and rmax <= RES_REL * NORM_D
                      and outside_err <= TOL_REL and all(x["found"] == x["multiplicity"] for x in mult))
        records.append(dict(common, slice=name, purpose=purpose, interval=[lo, hi], sigma=sigma,
                            k_requested=len(vals), eigenvalues_found=int(inside.sum()),
                            eigenvalues_expected=int(len(exact)), multiplicities=mult,
                            max_abs_error=max_err, tolerance=tol, max_residual_sym=rmax, residual_tolerance=RES_REL * NORM_D,
                            max_residual_original_D=max(res_orig, default=0.0),
                            out_of_slice_ritz_max_rel_err=outside_err, complete=complete,
                            solve_seconds=round(secs, 3), passed=passed,
                            timestamp=datetime.now(timezone.utc).isoformat()))
    fabric.close()

    all_pass = bool(structure_pass and z5.get("passed", True) and all(r["passed"] for r in records))
    for i, r in enumerate(records, 1):
        r["certificate_code"] = f"{MC_CODE}-S{i}"
    with open(args.out, "a") as f:
        for r in records:
            f.write(json.dumps(r) + "\n")
    # Sample machine_certificates row (public.machine_certificates columns; ids/owner/workspace left to the ingest
    # service) and the MC-*.json artifact in the E47-Kartekeya/certificates/ style.
    git = "e9be2deefb3e188b2a552be235ab73af173433bf"
    row = {
        "certificate_code": MC_CODE,
        "title": "E47 spectral fabric: distributed slice certification of D = L(x)I + I(x)K^2 (15625-dim)",
        "commit_sha": git,
        "environment": dict(common["env"], nodes=args.nodes, code_sha256=common["code_sha256"],
                            source="E47-Kartekeya website/interfaces/fcc-e47-spatial-lift/fcc_e47_validation.py",
                            implementation="classical simulation (numpy/scipy, multiprocessing)"),
        "residuals": {"dimension": n, "nnz": int(D.nnz), "kernel_dimension": structure["kernel_dim"],
                      "gap": structure["gap_numeric"], "gap_abs_err": structure["gap_abs_err"],
                      "gap_multiplicity": structure["gap_multiplicity"],
                      "max_slice_eig_err": max(r["max_abs_error"] for r in records),
                      "max_slice_residual": max(r["max_residual_sym"] for r in records),
                      "semigroup_max_rel_err": max(x["rel_err"] for x in structure["semigroup"]),
                      "full_spectrum_max_rel_err": structure["full_spectrum_max_rel_err"]},
        "result": {"status": "PASS" if all_pass else "FAIL", "certificate": MC_CODE,
                   "operator_sha256": common["operator_sha256"],
                   "partition": common["partition"],
                   "slices": [{"code": r["certificate_code"], "slice": r["slice"], "interval": r["interval"],
                               "found": r["eigenvalues_found"], "expected": r["eigenvalues_expected"],
                               "max_abs_error": r["max_abs_error"], "max_residual": r["max_residual_sym"],
                               "passed": r["passed"]} for r in records],
                   "semigroup": structure["semigroup"], "z5cube_crosscheck": z5.get("passed"),
                   "evidence_boundary": "Floating-point classical computation of a finite matrix spectrum; "
                                        "exact analytic spectrum lambda_FCC + ((c-6)(c-30))^2; not hardware evidence."},
        "valid": all_pass,
        "evidence_class": "E1",
        "access_scope": "workspace",
    }
    base = os.path.dirname(os.path.abspath(args.out))
    with open(os.path.join(base, "sample_machine_certificates_row.json"), "w") as f:
        json.dump(row, f, indent=2)
    mc = {"certificate_code": MC_CODE, "title": row["title"], "passed": all_pass,
          "checks": {"kernel_47": structure["kernel_dim"] == 47,
                     "gap_gamma_1e-10": structure["gap_abs_err"] <= 1e-10,
                     "gap_mult_376": structure["gap_multiplicity"] == 376,
                     "full_spectrum": structure["full_spectrum_max_rel_err"] <= 1e-12,
                     "semigroup_exp_minus_gamma_t": all(x["rel_err"] <= 1e-10 for x in structure["semigroup"]),
                     "z5cube_crosscheck": bool(z5.get("passed")),
                     **{r["slice"]: r["passed"] for r in records}},
          "dimension": n, "nnz": int(D.nnz), "gamma": structure["gap_numeric"],
          "gamma_exact": "(15-3*sqrt(5))/2", "commit_sha": git, "code_sha256": common["code_sha256"]}
    with open(os.path.join(base, f"{MC_CODE}.json"), "w") as f:
        json.dump(mc, f, indent=2)
    print(f"D {n}x{n} nnz={D.nnz} nodes={args.nodes} layout={fabric.layout} matvec_err={matvec_err:.1e} "
          f"trace {trace_D}=={trace_exact} frob_rel={common['global_checks']['frobenius2_rel_err']:.1e} wall={wall:.1f}s")
    print(f"structure: kernel={structure['kernel_dim']} gap={structure['gap_numeric']!r} err={structure['gap_abs_err']:.1e} "
          f"mult={structure['gap_multiplicity']} full_rel={structure['full_spectrum_max_rel_err']:.1e} "
          f"semigroup_max_rel={max(x['rel_err'] for x in structure['semigroup']):.1e} {'PASS' if structure_pass else 'FAIL'}")
    for r in records:
        print(f"{r['slice']:16s} [{r['interval'][0]}, {r['interval'][1]}] found {r['eigenvalues_found']:4d}/"
              f"{r['eigenvalues_expected']:<4d} maxerr={r['max_abs_error']:.2e} tol={r['tolerance']:.1e} "
              f"res={r['max_residual_sym']:.2e} resD={r['max_residual_original_D']:.2e} "
              f"complete={r['complete']} {'PASS' if r['passed'] else 'FAIL'}")
    print(f"z5cube cross-check: {z5.get('passed')}  ->  overall {'PASS' if all_pass else 'FAIL'}  ({MC_CODE})")
    return 0 if all_pass else 1


if __name__ == "__main__":
    sys.exit(main())
