"""Relationship-preserving probes beyond a fixed finite Gaussian example.

Decimal computations are numerical evidence, not interval certificates.  The
local coercivity theorem and the obstruction to deleting mixed terms are proved
in support-analysis.md.  No S13 section or representative is chosen.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import math
from pathlib import Path
import sys
import time

import mpmath as mp

ROOT = Path(__file__).resolve().parent
sys.path.insert(0, str(ROOT.parent / "riemann-2026-10-14"))
import kernel


def archimedean_constant():
    return mp.log(8 * mp.pi) + mp.euler + mp.pi / 2


def weight(u):
    return mp.exp(u / 2) / mp.sinh(u)


def tail_weight(length):
    """Exact elementary expression for integral_length^infinity weight(u) du."""
    length = mp.mpf(length)
    if length <= 0:
        raise ValueError("Support diameter must be positive")
    y = mp.exp(-length / 2)
    return 2 * mp.atanh(y) + 2 * mp.atan(y)


def local_margin(length, terms=3):
    """Evaluate a proved lower-bound expression, without certifying rounding.

    For log-support diameter L<=log(2), Q(g)>=margin*integral|g|^2 dx.
    Truncating the finite-chain sum gives a lower bound: omitted terms >=0.
    """
    length = mp.mpf(length)
    if not 0 < length <= mp.log(2):
        raise ValueError("Prime-free theorem requires 0 < diameter <= log(2)")
    if not isinstance(terms, int) or terms < 1:
        raise ValueError("terms must be a positive integer")
    return tail_weight(length) - archimedean_constant() + mp.fsum(
        (1 - mp.cos(mp.pi / (n + 1))) *
        (tail_weight(length / n) - tail_weight(length / (n - 1)))
        for n in range(2, terms + 1))


def full_arithmetic_matrix(basis, cutoff):
    """Compute both orientations; do not impose or average Hermitian entries."""
    names = ("endpoint", "prime_power_sum", "real_place_constant",
             "real_place_integral", "arithmetic_value")
    components = {name: mp.matrix(len(basis)) for name in names}
    for i in range(len(basis)):
        for j in range(len(basis)):
            result = kernel.arithmetic_entry(
                kernel.GaussianCorrelation(basis[j], basis[i]), cutoff)
            for name in names:
                components[name][i, j] = result[name]
    return components


def difference_probe(dps, epsilon="0.0001", order=4, cutoff=1000,
                     center="0.2", frequency="14", sigma="0.25"):
    """Near-null frequency-difference direction, preserving every complex term.

    psi(u)=Gaussian(u) exp(-it*u) (1-exp(-i epsilon*u))^order.
    The complete form tends to zero like O(epsilon^(2*order)); retaining only
    diagonal entries gives a nonvanishing answer.  Finite zero comparison is
    diagnostic and is not an enclosure of all zeros.
    """
    with mp.workdps(dps):
        eps = mp.mpf(epsilon)
        basis = [kernel.Gaussian(sigma, mp.mpf(frequency) + j * eps, center)
                 for j in range(order + 1)]
        coefficients = [mp.mpf((-1)**j * math.comb(order, j))
                        for j in range(order + 1)]
        parts = full_arithmetic_matrix(basis, cutoff)
        K = parts["arithmetic_value"]
        qparts = {name: kernel.quadratic(Kpart, coefficients)
                  for name, Kpart in parts.items()}
        diagonal = mp.fsum(abs(c)**2 * K[i, i]
                           for i, c in enumerate(coefficients))
        zeros = kernel.computed_zeros(20)
        # Sum the combined transform before squaring: avoids cancellation of
        # already formed near-equal matrix entries in this diagnostic.
        qzero = mp.fsum(mp.fsum(c * b.G(rho) for c, b in zip(coefficients, basis)) *
                       mp.conj(mp.fsum(c * b.G(1-mp.conj(rho))
                                      for c, b in zip(coefficients, basis)))
                       for rho in zeros)
        hermitian_residual = max(abs(K[i, j] - mp.conj(K[j, i]))
                                 for i in range(len(basis)) for j in range(len(basis)))
        # Schur pivots here are floating-point diagnostics, never certificates.
        pivots = []
        schur = K.copy()
        for n in range(len(basis)):
            p = schur[n, n]
            pivots.append(p)
            if not p:
                break
            for i in range(n + 1, len(basis)):
                for j in range(n + 1, len(basis)):
                    schur[i, j] -= schur[i, n] * schur[n, j] / p
        return kernel.encode({
            "status": "numerical evidence; no complete-tail or rounding certificate",
            "input": {"dps": dps, "epsilon": epsilon, "order": order,
                      "prime_cutoff": cutoff, "positive_zero_count": 20,
                      "sigma": sigma, "frequency": frequency, "log_center": center},
            "basis": [{"sigma": b.sigma, "frequency": b.t, "log_center": b.center}
                      for b in basis],
            "coefficients": coefficients,
            "matrix": K,
            "component_quadratic_forms": qparts,
            "complete_arithmetic_with_truncated_prime_sum": qparts["arithmetic_value"],
            "finite_reflected_zero_diagnostic": qzero,
            "diagonal_only_changed_calculation": diagonal,
            "mixed_term_contribution": qparts["arithmetic_value"] - diagonal,
            "hermitian_residual": hermitian_residual,
            "floating_schur_pivots": pivots,
            "counterexample_status": "not established",
            "inference_boundary": "A negative floating result or Schur pivot is not a negative complete-form certificate.",
        }, dps)


def run_search():
    started = time.monotonic()
    with mp.workdps(80):
        local = [{"diameter": length, "terms": n,
                  "lower_bound_expression_value": kernel.encode(local_margin(length, n)),
                  "status": "numerical evaluation of a proved analytic lower bound"}
                 for length, n in (("0.0625", 1), ("0.125", 3), ("0.125", 10),
                                   ("0.15", 10), ("0.15", 1000))]
        root = kernel.encode(mp.findroot(lambda L: local_margin(L, 1000), ("0.15", "0.16")))
        constant = kernel.encode(archimedean_constant())
    probes = [difference_probe(dps) for dps in (30, 80)]
    out = {"schema": "cooper-riemann-universal-search-v1",
           "status": "mixed analytic results and explicitly labelled numerical evidence",
           "general_RH": "unresolved",
           "source_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
           "kernel_sha256": hashlib.sha256(Path(kernel.__file__).read_bytes()).hexdigest(),
           "mpmath_version": mp.__version__,
           "local_coercivity": {"constant_A": constant, "evaluations": local,
                                "finite_1000_term_zero_of_margin_numerical": root,
                                "known_context": "Small-support positivity is established in prior work; this elementary coercive bound is weaker than the known log(2) support range."},
           "near_null_probes": probes,
           "relationship_constraints": ["Every ordered complex matrix entry is computed.",
                                        "No independently positive blocks are glued.",
                                        "No S13 section, global frame, representative, or gauge choice is assumed."],
           "elapsed_seconds": time.monotonic() - started}
    return out


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--output", type=Path, default=ROOT / "search-results.json")
    args = parser.parse_args()
    result = run_search()
    args.output.write_text(json.dumps(result, indent=2) + "\n")
    print(json.dumps({"output": str(args.output), "general_RH": result["general_RH"],
                      "elapsed_seconds": result["elapsed_seconds"]}))
