"""Rigorous infinite-dimensional positivity with all support interactions retained.

This proves a scoped theorem for sums of moment-zero compact smooth functions.
An inconclusive comparison matrix is never a negative Weil-form certificate.
Uses python-flint 0.8/0.9 and the frozen legacy exact-ball serialization helpers.
"""
from __future__ import annotations
import argparse
from copy import deepcopy
from fractions import Fraction
import hashlib
import json
from pathlib import Path
import sys

try:
    import certify as legacy
except ImportError:
    sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "riemann-2026-10-14"))
    import certify as legacy

SCHEMA = "cooper-riemann-reconstruction-v1"
KIND = "support_reconstruction"
MAX_WINDOWS = 12
MAX_PRIME_POWER = 50000
DEFAULT_WINDOWS = [["-1/40", "1/40"], ["27/40", "29/40"], ["55/40", "57/40"]]
METADATA = {
    "form_definition": "Q(g)=sum_rho G(rho)*conjugate(G(1-conjugate(rho))); the exact arithmetic explicit formula is used, with multiplicities.",
    "test_class": "g=sum_i g_i, phi_i(u)=exp(u/2)*g_i(exp(u)); each g_i is a complex smooth compactly supported function with log-support contained in its declared window.",
    "hypotheses": [
        "Every component g_i belongs to C_c^infinity(0,infinity).",
        "Each component separately satisfies G_i(0)=G_i(1)=0, equivalently integral exp(-u/2)*phi_i(u) du = integral exp(u/2)*phi_i(u) du = 0.",
        "The declared windows are ordered, pairwise disjoint, with positive gaps and each length less than log(2).",
        "All components are actual jointly specified scalar functions; the certificate does not manufacture geometric representatives or verify arbitrary uploaded functions."
    ],
    "compatibility_assumptions": [
        "The total function is the actual sum of the same components used in every diagonal and mixed term.",
        "Every unordered pair of windows is included; no prime or archimedean cross term is discarded.",
        "Separate local positivity statements are combined only through the complete comparison matrix and its verified Schur pivots.",
        "No global section, frame, spin lift, or choice of S13 representative is assumed.",
        "A partition of an arbitrary admissible function need not satisfy the separate moment constraints; this certificate does not assert that it does."
    ],
    "comparison_definition": "C_ii=m_N(length_i); C_ij=-(prime_bound_ij+archimedean_bound_ij). Q(sum g_i)>=v^T C v, where v_i=||g_i||_L2(dx).",
    "prime_selection_rule": "Enumerate every prime power up to a rigorously bounded exp(total span). Include every log(n) interval intersecting the closed window-difference interval; uncertain endpoints are included conservatively.",
    "archimedean_cancellation": "The exp(-u/2) leading kernel term vanishes for each mixed pair by the separate weighted moments; its remaining kernel is 2 exp(-5u/2)/(1-exp(-2u)).",
    "omitted_chain_terms": "Nonnegative by the translation-chain inequality, so dropping them gives a lower bound.",
    "claim": "If positivity_status is certified, Q(sum_i g_i) >= epsilon * sum_i integral |g_i(x)|^2 dx for every joint collection satisfying the hypotheses. Disjoint support makes this also epsilon*||sum_i g_i||_L2(dx)^2.",
    "scope": "Infinite-dimensional direct sum of the declared moment-zero support classes, with every mixed interaction controlled; not every admissible test.",
    "general_RH": "unresolved",
    "negative_result_scope": "Failure of this sufficient comparison bound is inconclusive; it is not a negative value of the complete Weil form."
}


def _canonical(value):
    return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=True, allow_nan=False)


def _digest(value):
    return hashlib.sha256(_canonical(value).encode()).hexdigest()


def _rational(value):
    if isinstance(value, bool) or not isinstance(value, (str, int)):
        raise ValueError("Use exact integer or rational/decimal strings; binary floats and booleans are rejected")
    return legacy.rational(value)


def _integer(value, lo, hi, name):
    if type(value) is not int or not lo <= value <= hi:
        raise ValueError(f"{name} must be an integer in [{lo},{hi}]")
    return value


def _normalize(windows, chain_terms, epsilon):
    if windows is None:
        windows = DEFAULT_WINDOWS
    if not isinstance(windows, list) or not 1 <= len(windows) <= MAX_WINDOWS:
        raise ValueError("Require 1..12 explicitly ordered support windows")
    parsed = []
    for item in windows:
        if not isinstance(item, list) or len(item) != 2:
            raise ValueError("Each window must be [exact left endpoint, exact right endpoint]")
        a, b = map(_rational, item)
        if not Fraction(1, 10**6) <= b-a <= 1:
            raise ValueError("Every support length must lie in [1e-6,1]")
        if parsed and a-parsed[-1][1] < Fraction(1, 10**6):
            raise ValueError("Windows must be ordered and disjoint with gaps at least 1e-6")
        parsed.append((a, b))
    if parsed[-1][1]-parsed[0][0] > 10:
        raise ValueError("Total support span must not exceed 10 for bounded exhaustive prime-power enumeration")
    terms = _integer(chain_terms, 1, 512, "chain_terms")
    eps = _rational(epsilon)
    if not 0 < eps <= 100:
        raise ValueError("epsilon must be a strictly positive exact number at most 100")
    return parsed, terms, eps


def _padded(x, bits):
    if not x.is_finite():
        raise ArithmeticError("Nonfinite arithmetic enclosure")
    f = legacy.backend()
    return x + f.arb(0, x.rad()/8 + (1+abs(x))*legacy.ar(Fraction(1, 2**(bits//3))))


def _ball_bounds(data):
    if not isinstance(data, dict):
        raise ValueError("A finite exact-dyadic ball is required")
    for key in ("midpoint_dyadic", "radius_dyadic"):
        pair = data.get(key)
        if not isinstance(pair, list) or len(pair) != 2 or not isinstance(pair[0], str) or type(pair[1]) is not int:
            raise ValueError("Malformed exact dyadic encoding")
        if len(pair[0]) > 2000 or not pair[0].lstrip("-").isdigit() or abs(pair[1]) > 10000:
            raise ValueError("Dyadic integer or exponent exceeds replay limits")
    return legacy.ball_bounds(data)


def _export(x, bits, padding):
    return legacy.ball_json(_padded(x, bits) if padding else x)


def _prime_powers(limit):
    """Exact sieve and integer exponentiation; each prime power occurs once."""
    flags = bytearray(b"\x01") * (limit+1)
    if limit >= 0:
        flags[0] = 0
    if limit >= 1:
        flags[1] = 0
    for p in range(2, limit+1):
        if not flags[p]:
            continue
        if p*p <= limit:
            flags[p*p:limit+1:p] = b"\x00" * ((limit-p*p)//p+1)
    powers = []
    for p in range(2, limit+1):
        if flags[p]:
            n, exponent = p, 1
            while n <= limit:
                powers.append((n, p, exponent))
                n *= p
                exponent += 1
    return sorted(powers)


def _diagonal(length, terms):
    f = legacy.backend()
    ll = legacy.ar(length)
    log_two = f.arb(2).log()
    if ll >= log_two:
        raise ValueError("Each window must have length strictly below log(2)")
    if not ll < log_two:
        raise ArithmeticError("Requested precision cannot distinguish the window length from log(2)")
    def B(x):
        y = (-x/2).exp()
        return ((1+y)/(1-y)).log() + 2*y.atan()
    A = (8*f.arb.pi()).log() + f.arb.const_euler() + f.arb.pi()/2
    tail = B(ll)
    contribution = f.arb(0)
    for n in range(2, terms+1):
        contribution += (1-(f.arb.pi()/(n+1)).cos())*(B(ll/n)-B(ll/(n-1)))
    return tail-A+contribution, A, tail, contribution


def _ldl(matrix):
    f = legacy.backend()
    size = len(matrix)
    lower = [[f.arb(0) for _ in range(size)] for _ in range(size)]
    pivots = []
    for i in range(size):
        d = matrix[i][i]
        for k in range(i):
            d -= pivots[k]*lower[i][k]*lower[i][k]
        if not d.is_finite():
            raise ArithmeticError("Nonfinite interval Schur pivot")
        pivots.append(d)
        if not d > 0:
            return False, pivots
        lower[i][i] = f.arb(1)
        for j in range(i+1, size):
            value = matrix[j][i]
            for k in range(i):
                value -= lower[j][k]*lower[i][k]*pivots[k]
            lower[j][i] = value/d
    return True, pivots


def _calculate(windows, terms, eps, bits, padding, recorded_selections=None, recorded_limit=None):
    f = legacy.backend()
    size = len(windows)
    span = windows[-1][1]-windows[0][0]
    # An upper endpoint for exp(span) proves no larger integer can qualify.
    exponential = legacy.ar(span).exp()
    upper = legacy.exact_fraction(exponential.upper())
    limit = (upper.numerator+upper.denominator-1)//upper.denominator
    if limit > MAX_PRIME_POWER:
        raise ValueError("Required exhaustive prime-power enumeration exceeds the interactive limit")
    if recorded_limit is not None:
        _integer(recorded_limit, 1, MAX_PRIME_POWER, "enumeration integer_limit")
        if recorded_limit < limit:
            raise ValueError("Recorded enumeration bound does not cover exp(total span)")
        limit = recorded_limit
    powers = _prime_powers(limit)
    exact_powers = {n: (p, k) for n, p, k in powers}
    logs = {n: legacy.ar(n).log() for n, _, _ in powers}
    weights = {p: legacy.ar(p).log() for _, p, _ in powers}
    matrix = [[f.arb(0) for _ in range(size)] for _ in range(size)]
    diagonals = []
    for i, (a, b) in enumerate(windows):
        m, A, tail, chain = _diagonal(b-a, terms)
        matrix[i][i] = m
        diagonals.append({"window": i, "length": str(b-a),
            "constant_A": _export(A, bits, padding), "tail_B": _export(tail, bits, padding),
            "finite_chain_contribution": _export(chain, bits, padding),
            "coercivity_margin": _export(m, bits, padding)})
    edges = []
    expected_keys = {f"{i}:{j}" for i in range(size) for j in range(i+1, size)}
    if recorded_selections is not None and set(recorded_selections) != expected_keys:
        raise ValueError("Certificate must retain exactly every unordered window pair")
    for i in range(size):
        for j in range(i+1, size):
            a, b = windows[i]
            c, d = windows[j]
            gap, far = c-b, d-a
            required = [n for n, _, _ in powers if not (logs[n] < legacy.ar(gap) or logs[n] > legacy.ar(far))]
            selected = required
            if recorded_selections is not None:
                selected = recorded_selections[f"{i}:{j}"]
                if not isinstance(selected, list) or any(type(n) is not int for n in selected):
                    raise ValueError("Prime-power selection must be an integer list")
                if selected != sorted(set(selected)) or any(n not in exact_powers for n in selected):
                    raise ValueError("Prime-power selections must be sorted distinct genuine prime powers within the exhaustive range")
                if not set(required) <= set(selected):
                    raise ValueError("A possibly contributing prime power is missing")
            prime = f.arb(0)
            records = []
            for n in selected:
                p, k = exact_powers[n]
                weight = weights[p]/legacy.ar(n).sqrt()
                prime += weight
                records.append({"n": n, "prime": p, "exponent": k,
                                "log_n": _export(logs[n], bits, padding),
                                "von_mangoldt_over_sqrt_n": _export(weight, bits, padding)})
            gg = legacy.ar(gap)
            arch = legacy.ar((b-a)*(d-c)).sqrt()*(-5*gg/2).exp()/(1-(-2*gg).exp())
            total = prime+arch
            matrix[i][j] = matrix[j][i] = -total
            edges.append({"i": i, "j": j, "difference_interval": [str(gap), str(far)],
                          "prime_powers": records,
                          "prime_bound": _export(prime, bits, padding),
                          "archimedean_bound": _export(arch, bits, padding),
                          "mixed_bound": _export(total, bits, padding)})
    shifted = [[matrix[i][j]-(legacy.ar(eps) if i == j else 0) for j in range(size)] for i in range(size)]
    positive, pivots = _ldl(shifted)
    exported_pivots = [_export(x, bits, padding) for x in pivots]
    positive = positive and all(_ball_bounds(x)[0] > 0 for x in exported_pivots)
    out = {"enumeration": {"integer_limit": limit, "prime_powers_enumerated": len(powers),
                           "total_log_span": str(span), "exponential_span": _export(exponential, bits, padding)},
           "local_bounds": diagonals, "interaction_edges": edges,
           "comparison_matrix": [[_export(x, bits, padding) for x in row] for row in matrix],
           "shifted_comparison_matrix": [[_export(x, bits, padding) for x in row] for row in shifted],
           "schur_pivots": exported_pivots,
           "coercivity_margin": str(eps) if positive else None,
           "strict_positivity": positive, "positivity_status": "certified" if positive else "inconclusive"}
    return out


def support_reconstruction(windows=None, chain_terms=64, epsilon="1/4", precision_bits=192):
    parsed, terms, eps = _normalize(windows, chain_terms, epsilon)
    bits = _integer(precision_bits, 80, 384, "precision_bits")
    with legacy.precision(bits) as f:
        out = _calculate(parsed, terms, eps, bits, padding=True)
        out.update({"schema": SCHEMA, "kind": KIND, "status": "certified_enclosures",
                    "precision_bits": bits,
                    "inputs": {"windows": [[str(a), str(b)] for a, b in parsed], "chain_terms": terms, "epsilon": str(eps)},
                    "backend": {"python_flint": f.__version__, "flint": getattr(f, "__FLINT_VERSION__", "unknown")},
                    **deepcopy(METADATA)})
        out["sha256"] = _digest(out)
        return out


def _check_enclosures(stored, fresh, path="certificate"):
    """Compare exact endpoints recursively; diagnostic displays are untrusted."""
    if isinstance(fresh, dict):
        if fresh.get("finite") is True and "midpoint_dyadic" in fresh:
            if not isinstance(stored, dict) or set(stored) != set(fresh):
                raise ValueError("Malformed ball at "+path)
            a, b = _ball_bounds(stored)
            c, d = _ball_bounds(fresh)
            if not a <= c <= d <= b:
                raise ValueError("Arithmetic enclosure failed recomputation at "+path)
            return
        if not isinstance(stored, dict) or set(stored) != set(fresh):
            raise ValueError("Certificate fields changed at "+path)
        for key in fresh:
            _check_enclosures(stored[key], fresh[key], path+"."+key)
    elif isinstance(fresh, list):
        if not isinstance(stored, list) or len(stored) != len(fresh):
            raise ValueError("Certificate list changed at "+path)
        for i, (a, b) in enumerate(zip(stored, fresh)):
            _check_enclosures(a, b, path+f"[{i}]")
    elif type(stored) is not type(fresh) or stored != fresh:
        raise ValueError("Certificate value changed at "+path)


def replay(certificate, extra_bits=32):
    if not isinstance(certificate, dict):
        raise ValueError("A certificate object is required")
    if certificate.get("schema") != SCHEMA or certificate.get("kind") != KIND:
        raise ValueError("Unsupported reconstruction certificate schema/kind")
    bits = _integer(certificate.get("precision_bits"), 80, 384, "precision_bits")
    extra = _integer(extra_bits, 16, 128, "extra_bits")
    unsigned = {k: v for k, v in certificate.items() if k != "sha256"}
    if certificate.get("sha256") != _digest(unsigned):
        raise ValueError("Certificate checksum differs; mathematical replay is also required")
    inputs = certificate.get("inputs")
    if not isinstance(inputs, dict) or set(inputs) != {"windows", "chain_terms", "epsilon"}:
        raise ValueError("Malformed certificate inputs")
    parsed, terms, eps = _normalize(**inputs)
    normalized = {"windows": [[str(a), str(b)] for a, b in parsed], "chain_terms": terms, "epsilon": str(eps)}
    if inputs != normalized:
        raise ValueError("Certificate inputs are not canonical")
    enumeration = certificate.get("enumeration")
    if not isinstance(enumeration, dict) or set(enumeration) != {"integer_limit", "prime_powers_enumerated", "total_log_span", "exponential_span"}:
        raise ValueError("Malformed exhaustive-enumeration record")
    selections = {}
    for edge in certificate.get("interaction_edges", []):
        key = f"{edge['i']}:{edge['j']}"
        if key in selections:
            raise ValueError("Duplicate mixed edge")
        selections[key] = [p["n"] for p in edge["prime_powers"]]
    with legacy.precision(bits+extra):
        fresh = _calculate(parsed, terms, eps, bits+extra, padding=False, recorded_selections=selections,
                           recorded_limit=enumeration["integer_limit"])
        # An interval decision that was inconclusive can improve at higher precision.
        # Replay preserves the recorded claim, then requires its positive assertion
        # to be supported by both the recorded and freshly recomputed pivots.
        positive = certificate.get("strict_positivity")
        if type(positive) is not bool:
            raise ValueError("Invalid positivity boolean")
        if positive:
            if not fresh["strict_positivity"] or len(certificate["schur_pivots"]) != len(parsed):
                raise ValueError("Recorded positive claim failed fresh Schur calculation")
            if any(_ball_bounds(x)[0] <= 0 for x in certificate["schur_pivots"]):
                raise ValueError("Recorded Schur interval is not strictly positive")
        # Replay must compare the full available Schur transcript. Different
        # stopping points can only cause a conservative replay rejection.
        fresh["strict_positivity"] = positive
        fresh["positivity_status"] = "certified" if positive else "inconclusive"
        fresh["coercivity_margin"] = str(eps) if positive else None
        fresh.update({"schema": SCHEMA, "kind": KIND, "status": "certified_enclosures",
                      "precision_bits": bits, "inputs": normalized,
                      "backend": certificate.get("backend"), **deepcopy(METADATA)})
        _check_enclosures(unsigned, fresh)
        return {"schema": SCHEMA, "kind": "support_reconstruction_replay", "status": "replayed",
                "recomputed": True, "verified_sha256": certificate["sha256"],
                "strict_positivity": positive, "positivity_status": fresh["positivity_status"],
                "epsilon": str(eps), "general_RH": "unresolved",
                "claim": METADATA["claim"]}


def dispatch(payload):
    try:
        if not isinstance(payload, dict):
            raise ValueError("Request must be an object")
        p = dict(payload)
        operation = p.pop("operation", KIND)
        if operation in (KIND, "reconstruction"):
            return support_reconstruction(**p)
        if operation == "replay":
            if "cert" in p and "certificate" in p:
                raise ValueError("Supply cert or certificate, not both")
            certificate = p.pop("cert", p.pop("certificate", None))
            return replay(certificate, **p)
        raise ValueError("Unknown operation")
    except (ValueError, TypeError, KeyError, OverflowError, RecursionError) as exc:
        return {"schema": SCHEMA, "kind": "error", "status": "invalid_input", "error": str(exc), "general_RH": "unresolved"}
    except ArithmeticError as exc:
        return {"schema": SCHEMA, "kind": "error", "status": "inconclusive", "error": str(exc), "general_RH": "unresolved"}
    except (RuntimeError, ImportError) as exc:
        return {"schema": SCHEMA, "kind": "error", "status": "unavailable", "error": str(exc), "general_RH": "unresolved"}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("operation", nargs="?", choices=[KIND, "reconstruction", "replay"])
    parser.add_argument("--input")
    parser.add_argument("--output")
    args = parser.parse_args()
    try:
        if args.input:
            with open(args.input, encoding="utf-8") as handle:
                text = handle.read(2_000_001)
        else:
            text = sys.stdin.read(2_000_001)
        if len(text) > 2_000_000:
            raise ValueError("Input exceeds two million characters")
        payload = json.loads(text) if text.strip() else {}
        if args.operation:
            payload["operation"] = args.operation
        result = dispatch(payload)
    except (ValueError, TypeError, OSError) as exc:
        result = {"schema": SCHEMA, "status": "invalid_input", "error": str(exc), "general_RH": "unresolved"}
    text = json.dumps(result, indent=2, ensure_ascii=False, allow_nan=False)+"\n"
    if args.output:
        Path(args.output).write_text(text)
    else:
        sys.stdout.write(text)
    return 0 if result["status"] in ("certified_enclosures", "replayed") else 2


if __name__ == "__main__":
    raise SystemExit(main())
