"""Relationship-preserving Riemann investigation, exploratory kernel.

Dependencies: mpmath==1.3.0. Pure Python; the same file runs under Pyodide.
All computed decimal outputs are NUMERICAL EVIDENCE, never ball certificates.
Mellin measure is dx/x; multiplicative correlation uses dy, not dy/y.
K[i,j] uses g_j first and conjugate(g_i) second, so Q(c)=c* K c.
"""
from functools import lru_cache
import json
import math

import mpmath as mp

VERSION = "1.0.0"
STATUS = "numerical evidence"


def number(value):
    """Decode a JSON real, [real,imag], or {re,im}; preserve decimal strings."""
    if isinstance(value, (list, tuple)):
        if len(value) != 2:
            raise ValueError("Complex numbers need [real, imaginary].")
        result = mp.mpc(str(value[0]), str(value[1]))
    elif isinstance(value, dict):
        result = mp.mpc(str(value.get("re", 0)), str(value.get("im", 0)))
    else:
        result = mp.mpf(str(value))
    if not mp.isfinite(result):
        raise ValueError("All inputs must be finite numbers.")
    return result


def encode(value, digits=None):
    digits = digits or mp.mp.dps
    if isinstance(value, mp.matrix):
        return [[encode(value[i, j], digits) for j in range(value.cols)]
                for i in range(value.rows)]
    if isinstance(value, (mp.mpc, complex)):
        return {"re": mp.nstr(mp.re(value), digits), "im": mp.nstr(mp.im(value), digits)}
    if isinstance(value, mp.mpf):
        return mp.nstr(value, digits)
    if isinstance(value, dict):
        return {key: encode(item, digits) for key, item in value.items()}
    if isinstance(value, (list, tuple)):
        return [encode(item, digits) for item in value]
    return value


def xi(s):
    """Entire completed function, with exact removable limits at 0 and 1."""
    s = mp.mpc(s)
    if s == 0 or s == 1:
        return mp.mpf("0.5")
    # Reflection avoids gamma poles at negative even integers as well.
    if mp.re(s) < mp.mpf("0.5"):
        s = 1 - s
    return s * (s - 1) * mp.power(mp.pi, -s / 2) * mp.gamma(s / 2) * mp.zeta(s) / 2


class Gaussian:
    """h(e^u)=exp(-u/2-it*u-(u-center)^2/(2*sigma^2)), g=D(D+1)h."""
    family = "rapidly decaying log-Gaussian; not compactly supported"

    def __init__(self, sigma="0.25", t=0, center=0):
        self.sigma, self.t, self.center = map(number, (sigma, t, center))
        if not all(mp.im(z) == 0 for z in (self.sigma, self.t, self.center)):
            raise ValueError("sigma, frequency and center must be real.")
        if self.sigma <= 0:
            raise ValueError("sigma must be positive.")

    def h_log(self, u):
        return mp.exp(-u / 2 - 1j * self.t * u - (u - self.center)**2 / (2 * self.sigma**2))

    def g_log(self, u):
        slope = -(u - self.center) / self.sigma**2 - mp.mpf("0.5") - 1j * self.t
        return (slope**2 + slope - 1 / self.sigma**2) * self.h_log(u)

    def H(self, s):
        z = s - mp.mpf("0.5") - 1j * self.t
        return mp.sqrt(2 * mp.pi) * self.sigma * mp.exp(self.center * z + self.sigma**2 * z**2 / 2)

    def G(self, s):
        return s * (s - 1) * self.H(s)

    def h(self, x):
        return self.h_log(mp.log(x))

    def g(self, x):
        return self.g_log(mp.log(x))


class Compact:
    """A C-infinity bump in log x, with support [exp(-L),exp(L)]."""
    family = "smooth compact support"

    def __init__(self, half_width=1, t=0):
        self.L, self.t = number(half_width), number(t)
        if mp.im(self.L) or mp.im(self.t) or self.L <= 0:
            raise ValueError("Real frequency and positive real half_width required.")

    def bump(self, u):
        if abs(u) >= self.L:
            return mp.mpf(0), mp.mpf(0), mp.mpf(0)
        v = 1 - (u / self.L)**2
        b = mp.exp(-1 / v)
        slope = -2 * u / (self.L**2 * v**2)
        curvature = -2 / (self.L**2 * v**2) - 8 * u**2 / (self.L**4 * v**3)
        return b, b * slope, b * (slope**2 + curvature)

    def h_log(self, u):
        return mp.exp((-mp.mpf("0.5") - 1j * self.t) * u) * self.bump(u)[0]

    def g_log(self, u):
        b, bp, bpp = self.bump(u)
        return mp.exp((-mp.mpf("0.5") - 1j * self.t) * u) * (bpp - 2j * self.t * bp - (self.t**2 + mp.mpf("0.25")) * b)

    def h(self, x):
        return self.h_log(mp.log(x))

    def g(self, x):
        return self.g_log(mp.log(x))

    def H(self, s):
        return mp.quad(lambda u: self.h_log(u) * mp.exp(s * u), [-self.L, 0, self.L])

    def G(self, s):
        return s * (s - 1) * self.H(s)

    def direct_G(self, s):
        return mp.quad(lambda u: self.g_log(u) * mp.exp(s * u), [-self.L, 0, self.L])

    def inverse(self, x):
        u = mp.log(x)
        if u <= -self.L:
            return mp.mpf(0)
        stop = min(u, self.L)
        points = [-self.L, stop] if stop <= 0 else [-self.L, 0, stop]
        first = mp.quad(self.g_log, points)
        second = mp.quad(lambda v: self.g_log(v) * mp.exp(v), points)
        return first - second / x


class GaussianCorrelation:
    """C_ij(u)=e^(u/2) f_ij(e^u), retaining both basis functions."""
    def __init__(self, first, second):
        if first.sigma != second.sigma:
            raise ValueError("This analytic correlation requires equal Gaussian widths.")
        self.first, self.second = first, second
        sigma = first.sigma
        self.a = 1 / (4 * sigma**2)
        self.delta = first.center - second.center
        self.b = (first.t + second.t) / 2
        self.A = 12 * self.a + mp.mpf("0.5")
        self.B = 12 * self.a**2 + self.a + mp.mpf("0.0625")
        self.base0 = mp.sqrt(mp.pi) * sigma * mp.exp(
            -self.a * self.delta**2 - sigma**2 * (first.t - second.t)**2 / 4
            - 1j * (first.t - second.t) * (first.center + second.center) / 2)
        self.r0 = 2 * self.a * self.delta - 1j * self.b
        self.c0 = self.base0 * self.polynomial(self.r0)

    def polynomial(self, r):
        return r**4 - self.A * r**2 + self.B

    def C(self, u):
        r = self.r0 - 2 * self.a * u
        return self.base0 * mp.exp(self.r0 * u - self.a * u**2) * self.polynomial(r)

    def f_log(self, u):
        return mp.exp(-u / 2) * self.C(u)

    def f(self, x):
        return self.f_log(mp.log(x))

    def mellin(self, s):
        return self.first.G(s) * mp.conj(self.second.G(1 - mp.conj(s)))

    def even_difference(self, u):
        """C(u)+C(-u)-2C(0), using O(u^2) quantities near zero."""
        d, r = 2 * self.a * u, self.r0
        p0 = self.polynomial(r)
        even_delta = d**2 * (6 * r**2 - self.A) + d**4
        peven = p0 + even_delta
        podd = d * (4 * r**3 - 2 * self.A * r) + 4 * r * d**3
        e = mp.exp(-self.a * u**2)
        cosine_minus_one = 2 * mp.sinh(r * u / 2)**2
        return 2 * self.base0 * (even_delta + peven * (mp.expm1(-self.a * u**2) + e * cosine_minus_one) - e * podd * mp.sinh(r * u))

    def real_place_integrand(self, u):
        if u == 0:
            return self.c0 / 2
        if abs(u) < mp.mpf("0.25"):
            numerator = mp.exp(u / 2) * self.even_difference(u) + 2 * self.c0 * mp.expm1(u / 2)
        else:
            numerator = mp.exp(u / 2) * (self.C(u) + self.C(-u)) - 2 * self.c0
        return numerator / (2 * mp.sinh(u))


@lru_cache(maxsize=16)
def prime_powers(cutoff):
    """Return (p^k,p,k) once each, including the cutoff endpoint."""
    cutoff = int(cutoff)
    sieve = bytearray(b"\x01") * (cutoff + 1)
    sieve[:2] = b"\x00\x00"
    for p in range(2, math.isqrt(cutoff) + 1):
        if sieve[p]:
            start = p * p
            sieve[start::p] = b"\x00" * (((cutoff - start) // p) + 1)
    result = []
    for p in range(2, cutoff + 1):
        if sieve[p]:
            n, exponent = p, 1
            while n <= cutoff:
                result.append((n, p, exponent))
                n, exponent = n * p, exponent + 1
    return tuple(sorted(result))


def arithmetic_entry(correlation, cutoff):
    """Bombieri explicit formula with finite prime sum, numerical real integral."""
    c = correlation
    endpoint = c.mellin(0) + c.mellin(1)
    prime = mp.fsum(mp.log(p) * (c.f(n) + c.f(mp.mpf(1) / n) / n)
                    for n, p, _ in prime_powers(cutoff))
    constant = (mp.log(4 * mp.pi) + mp.euler) * c.c0
    # Split around the Gaussian scale and its displaced centers. The final
    # interval is truly infinite; no finite upper quadrature cutoff is hidden.
    landmarks = {mp.mpf(0), mp.mpf("0.25"), mp.mpf("0.5"), mp.mpf(1), mp.mpf(2), mp.mpf(4), mp.mpf(8)}
    for offset in (-2, -1, 0, 1, 2):
        point = abs(c.delta) + offset * c.first.sigma
        if point > 0:
            landmarks.add(point)
    integral = mp.quad(c.real_place_integrand, sorted(landmarks) + [mp.inf])
    return {"endpoint": endpoint, "prime_power_sum": prime,
            "real_place_constant": constant, "real_place_integral": integral,
            "arithmetic_value": endpoint - prime - constant - integral}


@lru_cache(maxsize=12)
def _zeros_as_strings(count, dps):
    with mp.workdps(dps):
        # Round-trip every binary mantissa bit. Printing only dps significant
        # digits before caching otherwise introduces an avoidable rounding.
        return tuple(mp.nstr(mp.im(mp.zetazero(n)), dps + 10) for n in range(1, count + 1))


def computed_zeros(count):
    positive = [mp.mpc("0.5", t) for t in _zeros_as_strings(count, mp.mp.dps)]
    return positive + [mp.conj(rho) for rho in positive]


def zero_matrix(basis, zeros):
    return mp.matrix([[mp.fsum(gj.G(rho) * mp.conj(gi.G(1 - mp.conj(rho))) for rho in zeros)
                       for gj in basis] for gi in basis])


def quadratic(matrix, coefficients):
    c = mp.matrix(coefficients)
    return (c.transpose_conj() * matrix * c)[0]


def parse_basis(payload):
    sigma = payload.get("sigma", "0.25")
    frequencies = payload.get("frequencies", [0, 14, 21])
    centers = payload.get("centers", [0] * len(frequencies))
    if not 1 <= len(frequencies) <= 6 or len(centers) != len(frequencies):
        raise ValueError("Use 1–6 frequencies and one center per frequency.")
    if abs(number(sigma)) < mp.mpf("0.05") or abs(number(sigma)) > 2:
        raise ValueError("Browser exploration supports 0.05 <= sigma <= 2.")
    if any(abs(number(t)) > 80 for t in frequencies) or any(abs(number(m)) > 4 for m in centers):
        raise ValueError("Frequencies must be within ±80 and centers within ±4.")
    basis = [Gaussian(sigma, t, center) for t, center in zip(frequencies, centers)]
    coefficients = payload.get("coefficients", [[1, 0]] * len(basis))
    if len(coefficients) != len(basis):
        raise ValueError("Provide one complex coefficient per basis element.")
    return basis, [number(c) for c in coefficients]


def limits(payload):
    cutoff, count = int(payload.get("prime_cutoff", 1000)), int(payload.get("zero_count", 20))
    if not 2 <= cutoff <= 100000 or not 1 <= count <= 100:
        raise ValueError("prime_cutoff must be 2–100000 and zero_count 1–100.")
    return cutoff, count


def investigate_matrix(payload):
    basis, coefficients = parse_basis(payload)
    cutoff, count = limits(payload)
    n = len(basis)
    matrix, component_matrices = mp.matrix(n), {key: mp.matrix(n) for key in (
        "endpoint", "prime_power_sum", "real_place_constant", "real_place_integral")}
    # Compute both orientations. Hermiticity is checked, never imposed.
    for i, gi in enumerate(basis):
        for j, gj in enumerate(basis):
            entry = arithmetic_entry(GaussianCorrelation(gj, gi), cutoff)
            matrix[i, j] = entry["arithmetic_value"]
            for key, component in component_matrices.items():
                component[i, j] = entry[key]
    hermitian_residual = mp.norm(matrix - matrix.transpose_conj(), p=mp.inf)
    # eighe requires a Hermitian matrix; averaging numerical residuals is
    # disclosed and its norm reported independently.
    hermitian = (matrix + matrix.transpose_conj()) / 2
    eigenvalues, eigenvectors = mp.eighe(hermitian)
    zeros = computed_zeros(count)
    spectral = zero_matrix(basis, zeros)
    difference = matrix - spectral
    diagonal = mp.fsum(abs(c)**2 * matrix[j, j] for j, c in enumerate(coefficients))
    return {"matrix_arithmetic_truncated": matrix,
            "matrix_zero_truncated": spectral,
            "components": component_matrices,
            "eigenvalues_of_hermitian_part": list(eigenvalues),
            "eigenvectors_columns": eigenvectors,
            "lowest_direction_coefficients": [eigenvectors[i, 0] for i in range(n)],
            "hermitian_residual_max_entry": hermitian_residual,
            "symmetrization_error_max_entry": mp.norm(matrix - hermitian, p=mp.inf),
            "zero_comparison_max_entry": max(abs(z) for z in difference),
            "zero_comparison_frobenius": mp.norm(difference),
            "quadratic_value": quadratic(matrix, coefficients),
            "diagonal_only_changed_calculation": diagonal,
            "mixed_contribution": quadratic(matrix, coefficients) - diagonal,
            "component_quadratic_values": {key: quadratic(value, coefficients) for key, value in component_matrices.items()},
            "basis": [{"sigma": g.sigma, "frequency": g.t, "center": g.center} for g in basis],
            "coefficients": coefficients,
            "prime_power_cutoff": cutoff, "prime_power_count": len(prime_powers(cutoff)),
            "positive_zero_count": count, "zero_multiplicity_convention": "indices 1..N and conjugates, one entry per returned index",
            "cutoff_errors": {"prime_tail": "not certified", "zero_tail": "not certified", "quadrature": "not certified"},
            "admissibility": "Log-Gaussian entire Mellin transform with rapid vertical decay; this is an extended test family, not C_c^infinity."}


def explore_zeta(payload):
    s = number(payload.get("s", ["0.5", "14.134725141734693790457251983562"]))
    if abs(s) > 10000:
        raise ValueError("Use |s| <= 10000.")
    partner = 1 - mp.conj(s)
    kind = payload.get("point_kind", "evaluation point")
    if kind not in ("evaluation point", "synthetic"):
        raise ValueError("point_kind must be 'evaluation point' or 'synthetic'.")
    result = {"s": s, "reflected_partner": partner, "conjugate": mp.conj(s),
              "xi": xi(s), "xi_reflection_residual": xi(s) - xi(1 - s),
              "xi_conjugation_residual": xi(mp.conj(s)) - mp.conj(xi(s)),
              "point_kind": kind, "is_zero_certificate": False}
    if s == 1:
        result["zeta"] = "pole at s=1"
    else:
        result["zeta"] = mp.zeta(s)
        result["zeta_conjugation_residual"] = mp.zeta(mp.conj(s)) - mp.conj(mp.zeta(s))
        if mp.im(s) != 0 or mp.re(s) != int(mp.re(s)):
            reflected_zeta = 2**s * mp.pi**(s-1) * mp.sin(mp.pi*s/2) * mp.gamma(1-s) * mp.zeta(1-s)
            result["zeta_functional_equation_residual"] = mp.zeta(s) - reflected_zeta
        else:
            result["zeta_functional_equation_residual"] = "Use the entire completed identity at integer arguments where separate factors have zeros or poles."
    if "zero_index" in payload:
        index = int(payload["zero_index"])
        if not 1 <= index <= 100:
            raise ValueError("zero_index must be 1–100.")
        rho = computed_zeros(index)[index - 1]
        result["computed_zero"] = {"index": index, "rho": rho, "zeta_residual": mp.zeta(rho),
                                   "status": STATUS, "total_region_count": "not established by this routine"}
    return result


def explore_test(payload):
    family = payload.get("family", "compact")
    if family not in ("compact", "gaussian"):
        raise ValueError("family must be compact or gaussian.")
    if family == "compact":
        L = number(payload.get("half_width", 1))
        if not mp.mpf("0.1") <= L <= 4:
            raise ValueError("half_width must be 0.1–4.")
        test = Compact(L, payload.get("t", 0))
    else:
        test = Gaussian(payload.get("sigma", ".25"), payload.get("t", 0), payload.get("center", 0))
        if not mp.mpf("0.05") <= test.sigma <= 2 or abs(test.center) > 4:
            raise ValueError("Use 0.05 <= sigma <= 2 and |center| <= 4.")
    s, x = number(payload.get("s", ["0.5", 14])), number(payload.get("x", 1))
    if mp.im(x) or x <= 0:
        raise ValueError("x must be a positive real number.")
    if abs(test.t) > 80 or abs(s) > 100:
        raise ValueError("Use |frequency| <= 80 and |s| <= 100.")
    u = mp.log(x)
    derivative_value = mp.diff(test.h_log, u, 2) + mp.diff(test.h_log, u)
    result = {"family": test.family, "x": x, "h": test.h(x), "g": test.g(x),
              "differential_identity_residual": derivative_value - test.g(x),
              "s": s, "H": test.H(s), "G": test.G(s),
              "moments_from_algebra": {"G(0)": test.G(0), "G(1)": test.G(1)},
              "identity": "G(s)=s(s-1)H(s)"}
    if isinstance(test, Compact):
        direct = test.direct_G(s)
        result.update({"support_interval": [mp.exp(-test.L), mp.exp(test.L)],
                       "direct_Mellin": direct, "Mellin_identity_residual": direct - test.G(s),
                       "moments_direct_quadrature": {"G(0)": test.direct_G(0), "G(1)": test.direct_G(1)},
                       "inverse_h": test.inverse(x), "inverse_residual": test.inverse(x) - test.h(x),
                       "boundary_regularness": "The analytic bump and every derivative vanish at both endpoints; numerical samples are not the proof."})
    else:
        result["support_interval"] = "(0,infinity); rapid decay in log x"
    return result


def explore_correlation(payload):
    first = Gaussian(payload.get("sigma", ".25"), payload.get("t_j", 14), payload.get("center_j", 0))
    second = Gaussian(payload.get("sigma", ".25"), payload.get("t_i", 0), payload.get("center_i", 0))
    if not mp.mpf("0.05") <= first.sigma <= 2 or max(abs(first.t),abs(second.t)) > 80 or max(abs(first.center),abs(second.center)) > 4:
        raise ValueError("Use 0.05 <= sigma <= 2, |frequencies| <= 80 and |centers| <= 4.")
    c = GaussianCorrelation(first, second)
    x, s = number(payload.get("x", 1)), number(payload.get("s", ["0.5", 14]))
    if mp.im(x) or x <= 0:
        raise ValueError("x must be positive and real.")
    if abs(s) > 100 or abs(mp.log(x)) > 10:
        raise ValueError("Use |s| <= 100 and |log x| <= 10.")
    u = mp.log(x)
    # Direct dy quadrature is in v=log y, with dy=e^v dv.
    midpoint = (first.center + second.center - u) / 2
    spread = first.sigma
    points = [mp.ninf] + [midpoint + k * spread for k in (-4, -2, 0, 2, 4)] + [mp.inf]
    direct = mp.quad(lambda v: first.g_log(u + v) * mp.conj(second.g_log(v)) * mp.exp(v), points)
    support_center = first.center - second.center
    mellin_points = [mp.ninf] + [support_center + k * spread for k in (-4, -2, 0, 2, 4)] + [mp.inf]
    direct_mellin = mp.quad(lambda v: c.C(v) * mp.exp((s - mp.mpf("0.5")) * v), mellin_points)
    return {"index_order": "first=g_j, second=g_i; K_ij has coefficient conjugate(c_i)*c_j",
            "x": x, "correlation_analytic": c.f(x), "correlation_direct_dy": direct,
            "correlation_residual": direct - c.f(x), "s": s,
            "Mellin_direct": direct_mellin, "Mellin_reflected_product": c.mellin(s),
            "Mellin_identity_residual": direct_mellin - c.mellin(s),
            "wrong_absolute_square_for_comparison": abs(first.G(s))**2,
            "reflected_partner": 1 - mp.conj(s)}


def explore_prime_zero(payload):
    x = number(payload.get("x", 100))
    count = int(payload.get("zero_count", 20))
    if mp.im(x) or not 1 < x <= 100000 or not 1 <= count <= 100:
        raise ValueError("Use 1 < x <= 100000 and 1 <= zero_count <= 100.")
    terms = prime_powers(int(mp.floor(x)))
    psi0 = mp.fsum(mp.log(p) * (mp.mpf("0.5") if n == x else 1) for n, p, _ in terms)
    j0 = mp.fsum(mp.mpf(1) / k * (mp.mpf("0.5") if n == x else 1) for n, p, k in terms)
    primes = [p for n, p, k in terms if k == 1]
    pi0 = mp.fsum(mp.mpf("0.5") if p == x else 1 for p in primes)
    zeros = computed_zeros(count)
    zero_sum = mp.fsum(mp.power(x, rho) / rho for rho in zeros)
    constant = -mp.log(2 * mp.pi)
    trivial = -mp.log1p(-x**-2) / 2
    approximation = x - zero_sum + constant + trivial
    # For J0 use Ei(rho log x) on its principal branch. Pairing conjugates
    # cancels the branch-imaginary constants and is stated explicitly.
    jzero = mp.fsum(mp.ei(rho * mp.log(x)) for rho in zeros)
    jtrivial = mp.quad(lambda u: 1 / (u * mp.expm1(2 * u)), [mp.log(x), mp.inf])
    japprox = mp.li(x) - jzero - mp.log(2) + jtrivial
    return {"x": x, "prime_count_pi": len(primes), "prime_count_midpoint_pi0": pi0,
            "weighted_prime_power_psi0": psi0, "prime_power_count_J0": j0,
            "jump_convention": "At x=p^k, the endpoint contributes half its weight to psi0 and J0; pi0 uses half at primes.",
            "psi_zero_sum_truncated": zero_sum, "psi_main_term": x,
            "psi_endpoint_constant": constant, "psi_trivial_zero_term": trivial,
            "psi_approximation": approximation, "psi_difference": psi0 - approximation,
            "J_zero_sum_truncated": jzero, "J_trivial_zero_integral": jtrivial,
            "J_approximation": japprox, "J_difference": j0 - japprox,
            "positive_zero_count": count,
            "zero_summation_convention": "symmetric positive/negative ordinates from the first N computed critical-line zeros; omitted zeros not bounded",
            "error_bounds": {"arithmetic_count": "finite enumeration, with exploratory decimal logarithms", "zero_tail": "not certified", "RH_dependent_estimate": "none asserted"}}


def check_claim(payload):
    """Check explicit logical prerequisites; never promote float evidence."""
    claim = payload.get("claim", "finite_positive_matrix_implies_RH")
    if claim == "finite_positive_matrix_implies_RH":
        return {"verdict": "contradicted", "target": "the stated implication, not RH",
                "reason": "Positivity on a finite-dimensional subspace does not imply positivity on the full Weil test space.",
                "countermodel": "On span(e1,e2), Q(a,b)=|a|^2-|b|^2 is positive on span(e1) but negative at e2.",
                "missing_hypotheses": ["exhaustive dense test spaces", "justified convergence and tails", "positivity for every admissible test"]}
    if claim == "synthetic_pair":
        # Anti-diagonal reflection pairing has eigenvalues ±1; this is a
        # finite-dimensional toy calculation, never a zeta-zero certificate.
        a, b = number(payload.get("a", [1, 0])), number(payload.get("b", [-1, 0]))
        return {"verdict": STATUS, "classification": "synthetic reflected-pair toy model; not computed zeta zeros",
                "paired_value": a * mp.conj(b) + b * mp.conj(a),
                "replaced_absolute_squares": abs(a)**2 + abs(b)**2,
                "reason": "Replacing the reflected partner changes the quadratic form away from the critical line."}
    if claim == "off_line_zero":
        s = number(payload.get("s", ["0.6", 14]))
        return {"verdict": "inconclusive", "candidate": s, "zeta_residual": mp.zeta(s) if s != 1 else "pole",
                "reason": "A floating-point candidate or residual is not an existence enclosure with multiplicity and a real-part interval excluding 1/2.",
                "required_certificate": ["rigorous existence/isolation", "nontrivial region", "real enclosure excludes 1/2", "backend assumptions and precision receipt"]}
    if claim == "negative_form":
        return {"verdict": "inconclusive", "submitted_value": payload.get("value"),
                "reason": "A numerical negative value cannot certify a complete negative Weil form.",
                "required_certificate": ["admissible function and moments", "input balls", "all arithmetic and zero tails", "quadrature enclosure", "strictly negative rigorous upper bound"]}
    raise ValueError("Unknown claim. Use finite_positive_matrix_implies_RH, synthetic_pair, off_line_zero or negative_form.")


def dispatch(payload):
    """Stable website/CLI entry point; errors are explicit JSON objects."""
    try:
        if isinstance(payload, str):
            payload = json.loads(payload)
        if not isinstance(payload, dict):
            raise ValueError("Inputs must be a JSON object.")
        operation = payload.get("operation", payload.get("op", "matrix"))
        dps = int(payload.get("dps", 40))
        if not 20 <= dps <= 100:
            raise ValueError("dps must be 20–100.")
        handlers = {"zeta": explore_zeta, "test_function": explore_test,
                    "correlation": explore_correlation, "explicit_formula": investigate_matrix,
                    "matrix": investigate_matrix, "prime_zero": explore_prime_zero, "checker": check_claim}
        if operation not in handlers:
            raise ValueError("Unknown operation: " + str(operation))
        with mp.workdps(dps):
            result = handlers[operation](payload)
            status = result.get("verdict", STATUS)
            return {"schema_version": 1, "kernel_version": VERSION, "operation": operation,
                    "status": status, "precision_dps": dps, "backend": "mpmath " + mp.__version__,
                    "inputs": payload, "result": encode(result, dps),
                    "limitations": ["Exploratory arbitrary-precision arithmetic is not interval or ball certification.",
                                    "Finite primes, zeros, and basis dimensions do not establish the universal positivity required by RH.",
                                    "Higher precision and a small residual alone do not certify the omitted tails."]}
    except (ValueError, TypeError, KeyError, ArithmeticError) as exc:
        return {"schema_version": 1, "kernel_version": VERSION, "status": "error", "error": str(exc)}


def dispatch_json(payload):
    return json.dumps(dispatch(payload), ensure_ascii=False, allow_nan=False)
