"""Numerical candidate search for complete separated-window comparison bounds.

All decimal results are numerical evidence.  Rigorous ball certificates are
produced independently.  A failed comparison bound is not a negative Weil form.
Each scalar summand must separately satisfy BOTH Mellin moment constraints.
No geometric section, S13 representative, or gluing hypothesis is introduced.
"""
from __future__ import annotations

import argparse
from fractions import Fraction
from functools import lru_cache
import hashlib
import json
from pathlib import Path

import mpmath as mp

ROOT = Path(__file__).resolve().parent


def exact(value):
    if isinstance(value, bool) or not isinstance(value, (str, int, Fraction)):
        raise ValueError("Use exact rational strings or integers for window endpoints.")
    return Fraction(value)


def real(value):
    value = exact(value)
    return mp.mpf(value.numerator) / value.denominator


def encode(value):
    if isinstance(value, mp.matrix):
        return [[encode(value[i, j]) for j in range(value.cols)] for i in range(value.rows)]
    if isinstance(value, mp.mpf):
        return mp.nstr(value, mp.mp.dps)
    if isinstance(value, Fraction):
        return str(value)
    if isinstance(value, dict):
        return {k: encode(v) for k, v in value.items()}
    if isinstance(value, (list, tuple)):
        return [encode(v) for v in value]
    return value


def B(length):
    y = mp.exp(-length / 2)
    return 2 * mp.atanh(y) + 2 * mp.atan(y)


def local_margin(length, terms=64):
    if not 0 < length <= mp.log(2):
        raise ValueError("The local bound requires 0 < support diameter <= log(2).")
    if type(terms) is not int or not 1 <= terms <= 1024:
        raise ValueError("Use 1..1024 finite-chain terms.")
    A = mp.log(8 * mp.pi) + mp.euler + mp.pi / 2
    return B(length) - A + mp.fsum(
        (1-mp.cos(mp.pi/(n+1))) * (B(length/n)-B(length/(n-1)))
        for n in range(2, terms+1))


@lru_cache(maxsize=8)
def prime_powers(limit):
    """Enumerate every prime power once; composites with two prime bases vanish."""
    if not 2 <= limit <= 500_000:
        raise ValueError("Prime-power enumeration limit must be 2..500000.")
    sieve = bytearray(b"\x01") * (limit+1)
    sieve[0:2] = b"\x00\x00"
    for p in range(2, int(limit**0.5)+1):
        if sieve[p]:
            sieve[p*p:limit+1:p] = b"\x00" * ((limit-p*p)//p+1)
    result = []
    for p in range(2, limit+1):
        if sieve[p]:
            n, exponent = p, 1
            while n <= limit:
                result.append((n, p, exponent))
                n *= p
                exponent += 1
    return tuple(sorted(result))


def windows_at(centers, length="1/20"):
    half = exact(length)/2
    return [{"id": f"window-{i}", "left": str(exact(c)-half),
             "right": str(exact(c)+half)} for i, c in enumerate(centers)]


def normalize_windows(windows):
    if not isinstance(windows, list) or not 1 <= len(windows) <= 16:
        raise ValueError("Provide 1..16 strictly separated ordered windows.")
    result = []
    for i, w in enumerate(windows):
        if not isinstance(w, dict) or set(w)-{"id", "left", "right"}:
            raise ValueError("A window has id, left, and right fields only.")
        a, b = exact(w["left"]), exact(w["right"])
        ident = w.get("id", f"window-{i}")
        if not isinstance(ident, str) or not 1 <= len(ident) <= 80:
            raise ValueError("Window ids must be nonempty text of at most 80 characters.")
        if not a < b or b-a > Fraction(1, 2):
            raise ValueError("Each window length must lie in (0,1/2].")
        if result and a <= result[-1]["right"]:
            raise ValueError("Windows must be ordered and strictly separated.")
        result.append({"id": ident, "left": a, "right": b})
    if len({w["id"] for w in result}) != len(result):
        raise ValueError("Window ids must be unique.")
    if result[-1]["right"]-result[0]["left"] > 10:
        raise ValueError("This bounded search supports total logarithmic span <=10.")
    return result


def archimedean_bound(length_i, length_j, gap):
    if gap <= 0:
        raise ValueError("The moment-suppressed bound requires a strictly positive gap.")
    # The factor 1/2 in the polarized arithmetic term cancels the factor 2
    # in w(u)=2 sum_{k>=0} exp(-(2k+1/2)u). Local moments annihilate k=0.
    return mp.sqrt(length_i*length_j)*mp.exp(-mp.mpf("2.5")*gap)/(-mp.expm1(-2*gap))


def comparison(windows, chain_terms=64):
    ws = normalize_windows(windows)
    widths = [real(w["right"]-w["left"]) for w in ws]
    margins = [local_margin(L, chain_terms) for L in widths]
    C = mp.diag(margins)
    span = ws[-1]["right"]-ws[0]["left"]
    limit = max(2, int(mp.ceil(mp.exp(real(span)))))
    powers = prime_powers(limit)
    pairs = []
    for i in range(len(ws)):
        for j in range(i+1, len(ws)):
            lo = ws[j]["left"]-ws[i]["right"]
            hi = ws[j]["right"]-ws[i]["left"]
            terms = [{"n": n, "prime": p, "exponent": exponent,
                      "weight": mp.log(p)/mp.sqrt(n)}
                     for n, p, exponent in powers if real(lo) <= mp.log(n) <= real(hi)]
            prime = mp.fsum(t["weight"] for t in terms)
            arch = archimedean_bound(widths[i], widths[j], real(lo))
            total = prime+arch
            C[i, j] = C[j, i] = -total
            pairs.append({"i": i, "j": j, "window_ids": [ws[i]["id"], ws[j]["id"]],
                          "difference_interval": [lo, hi], "gap": lo,
                          "prime_power_terms": terms, "prime_bound": prime,
                          "archimedean_bound": arch, "total_mixed_bound": total,
                          "interaction_retained": True})
    eigenvalues = mp.eigsy(C, eigvals_only=True)
    row_margins = [C[i, i]-mp.fsum(abs(C[i, j]) for j in range(C.cols) if j != i)
                   for i in range(C.rows)]
    return {"windows": ws, "chain_terms": chain_terms, "total_span": span,
            "span_exceeds_log_2": real(span) > mp.log(2),
            "prime_enumeration_limit": limit,
            "local_coercivity_margins": margins, "pairs": pairs,
            "comparison_matrix": C, "eigenvalues": list(eigenvalues),
            "minimum_eigenvalue": eigenvalues[0], "row_margins": row_margins,
            "minimum_row_margin": min(row_margins),
            "numerical_candidate_status": "positive_comparison_candidate" if eigenvalues[0] > 0 else "comparison_bound_not_positive",
            "actual_form_counterexample": "not_established",
            "hypotheses": ["Each g_j is a specified smooth compactly supported scalar function whose log support lies in its recorded window.",
                           "Each g_j separately satisfies G_j(0)=G_j(1)=0; aggregate moment cancellation alone is not sufficient.",
                           "The complete reflected Weil form, including every mixed term, is used."],
            "analytic_implication": "If an independently verified C >= epsilon I with epsilon>0 holds, then Q(sum_j g_j) >= epsilon sum_j integral |g_j(x)|^2 dx for every such tuple.",
            "status": "numerical evidence; not a ball certificate",
            "no_gluing_assumption": "This is a bound on a supplied scalar sum, not an inference that unspecified local geometric data glue or admit a global section."}


def numerical_ldl(matrix, epsilon="0"):
    """Diagnostic pivots only; no outward rounding enclosure is claimed."""
    n = matrix.rows
    A = matrix-mp.eye(n)*real(epsilon)
    L = mp.eye(n)
    pivots = []
    for i in range(n):
        d = A[i, i]-mp.fsum(pivots[k]*L[i, k]**2 for k in range(i))
        pivots.append(d)
        if d <= 0:
            break
        for j in range(i+1, n):
            L[j, i] = (A[j, i]-mp.fsum(L[j, k]*L[i, k]*pivots[k] for k in range(i)))/d
    return pivots


def run_search(dps=70):
    if type(dps) is not int or not 30 <= dps <= 150:
        raise ValueError("Use 30..150 decimal digits.")
    cases = [
        ("two_prime_2_windows", ["0", "7/10"], "9/100", "1/20"),
        ("three_prime_power_triangle", ["0", "7/10", "7/5"], "1/20", "1/4"),
        ("six_windows_prime_5", ["0", "2/5", "4/5", "6/5", "8/5", "2"], "1/20", "2/5"),
        ("six_windows_prime_2_and_5", ["0", "2/5", "7/10", "6/5", "8/5", "2"], "1/20", "1/4"),
        ("six_wider_windows", ["0", "2/5", "7/10", "6/5", "8/5", "2"], "3/50", "0"),
        ("seven_windows_prime_2_5_11", ["0", "2/5", "7/10", "6/5", "8/5", "2", "12/5"], "1/20", "1/100"),
        ("eight_windows_comparison_failure", ["0", "2/5", "7/10", "6/5", "8/5", "2", "12/5", "14/5"], "1/20", "0"),
        ("two_wider_windows_comparison_failure", ["0", "7/10"], "1/10", "0"),
    ]
    with mp.workdps(dps):
        results = []
        for name, centers, width, epsilon in cases:
            out = comparison(windows_at(centers, width))
            out["name"] = name
            out["candidate_epsilon"] = epsilon
            out["numerical_shifted_ldl_pivots"] = numerical_ldl(out["comparison_matrix"], epsilon)
            results.append(encode(out))
    return {"schema": "cooper-riemann-window-search-v1", "status": "numerical candidates and explicitly identified comparison failures",
            "dps": dps, "mpmath_version": mp.__version__,
            "source_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
            "cases": results, "general_RH": "unresolved",
            "scope": "Infinite-dimensional locally moment-zero classes inside specified separated windows; a rigorous sign claim requires the independent ball certificate."}


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