"""Certify the existing T15 entries without changing or publishing numbers.

Run with Python 3, despite the historical .sage attachment name:

    python3 -B generate.sage table.json

Requires python-flint (tested with the already installed version 0.6.0).
table.json is a complete NumberDB JSON export, including Numbers. The command
prints a JSON report and exact dyadic certificates; it writes no files and
makes no network requests. There is no publication mode.

This replaces the legacy heuristic symbolic-derivative/interval exporter.
The original source remains in revision history. Its conversion of scalar
approximations to intervals is not used as a certificate here.

All arithmetic below uses Arb balls, including zeta and gamma power series.
The exact centre is 1/2. The coefficient of the series variable to degree n
is a_n/n!; multiplying by the exact factorial gives a_n. The functional
equation xi(s)=xi(1-s) proves the odd entries are exactly zero.

The fixed 3072-bit working precision was measured on the full degree-250
series: at least 1210 relative-accuracy bits remained in the nonzero entries.
This is not a guessed error bound: each written decimal interval must contain
the entire computed enclosure. A gamma-recurrence formulation at 3584 bits
cross-checks every coefficient. Certificate endpoints are rounded outward to
384 bits and checked again using exact rational arithmetic.

The explicit limits match this bounded repair, not a claim about larger n.
"""

import argparse
import hashlib
import json
import math
import resource
import time
from decimal import Decimal
from fractions import Fraction
from pathlib import Path

import flint
from flint import arb, arb_series, ctx, fmpq


RIGOUR = "proven"
MAX_ORDER = 250
WORKING_BITS = 3072
CROSS_CHECK_BITS = 3584
CERTIFICATE_BITS = 384


def require(condition, message):
    if not condition:
        raise ArithmeticError(message)


def rational_ball(value):
    return arb(fmpq(value.numerator, value.denominator))


def taylor_coefficients(bits, gamma_recurrence=False):
    ctx.prec = bits
    ctx.cap = MAX_ORDER + 1
    ctx.threads = 1
    variable = arb_series([arb(1) / 2, 1])
    exponential = (-variable * arb.pi().log() / 2).exp()
    if gamma_recurrence:
        series = (
            (variable - 1) * exponential
            * (1 + variable / 2).gamma() * variable.zeta()
        )
    else:
        series = (
            variable * (variable - 1) * exponential
            * (variable / 2).gamma() * variable.zeta() / 2
        )
    return [series[index] for index in range(MAX_ORDER + 1)]


def exact_bound(ball, upper):
    previous_bits = ctx.prec
    try:
        ctx.prec = CERTIFICATE_BITS
        endpoint = ball.upper() if upper else ball.lower()
        mantissa, exponent = endpoint.man_exp()
        return [str(mantissa), int(exponent)]
    finally:
        ctx.prec = previous_bits


def dyadic_fraction(endpoint):
    mantissa, exponent = endpoint
    return Fraction(int(mantissa)) * Fraction(2) ** exponent


def certify(document):
    started = time.monotonic()
    numbers = document["Numbers"]
    expressions = ("a_n", "a_n/n!")
    require(list(numbers) == list(expressions), "Unexpected expression identities")
    expected_indices = [str(index) for index in range(MAX_ORDER + 1)]
    for expression in expressions:
        require(list(numbers[expression]) == expected_indices, "Unexpected order range")

    coefficients = taylor_coefficients(WORKING_BITS)
    primary_seconds = time.monotonic() - started
    independent_form = taylor_coefficients(CROSS_CHECK_BITS, gamma_recurrence=True)
    ctx.prec = WORKING_BITS
    for index in range(MAX_ORDER + 1):
        require(coefficients[index].is_finite(), "Nonfinite primary coefficient")
        require(independent_form[index].is_finite(), "Nonfinite cross-check coefficient")
        require(coefficients[index].overlaps(independent_form[index]), "Cross-check mismatch")

    scalar_control = (
        -(arb(1) / 4).gamma() * (arb(1) / 2).zeta()
        / (8 * (arb.pi().log() / 4).exp())
    )
    require(scalar_control.is_finite(), "Nonfinite scalar control")
    require(coefficients[0].overlaps(scalar_control), "Wrong normalization at 1/2")

    certificates = []
    exact_zero_identities = []
    shifted_controls = 0
    minimum_accuracy = WORKING_BITS
    maximum_radius_units = arb(0)
    for expression in expressions:
        for index_text, entry in numbers[expression].items():
            index = int(index_text)
            written = entry["number"] if isinstance(entry, dict) else entry
            scale = math.factorial(index) if expression == "a_n" else 1
            enclosure = coefficients[index] * scale
            cross_check = independent_form[index] * scale
            identity = [expression, index_text]
            require(enclosure.is_finite() and cross_check.is_finite(), str(identity))
            if index % 2:
                require(written == "0", "Odd entry is not exact zero")
                require(enclosure.contains(0) and cross_check.contains(0), str(identity))
                require(not enclosure.contains(1), "Vacuous odd-coefficient enclosure")
                exact_zero_identities.append(identity)
                continue

            center = Fraction(written)
            unit = Fraction(10) ** Decimal(written).as_tuple().exponent
            lower = center - unit
            upper = center + unit
            for candidate in (enclosure, cross_check):
                require(
                    candidate.lower() > rational_ball(lower).upper()
                    and candidate.upper() < rational_ball(upper).lower(),
                    "Enclosure exceeds written interval: " + str(identity),
                )
            lower_endpoint = exact_bound(enclosure, upper=False)
            upper_endpoint = exact_bound(enclosure, upper=True)
            certified_lower = dyadic_fraction(lower_endpoint)
            certified_upper = dyadic_fraction(upper_endpoint)
            require(
                lower < certified_lower <= certified_upper < upper,
                "Outward-rounded certificate exceeds written interval: " + str(identity),
            )
            for displacement in (-4, 4):
                shifted_center = center + displacement * unit
                require(
                    certified_upper < shifted_center - unit
                    or certified_lower > shifted_center + unit,
                    "Shifted interval was not rejected: " + str(identity),
                )
                shifted_controls += 1
            minimum_accuracy = min(minimum_accuracy, enclosure.rel_accuracy_bits())
            radius_units = (enclosure.rad() / rational_ball(unit)).upper()
            require(radius_units < arb(1) / 100, "Enclosure is too wide")
            if radius_units > maximum_radius_units:
                maximum_radius_units = radius_units
            certificates.append({
                "identity": identity,
                "written": written,
                "lower_dyadic": lower_endpoint,
                "upper_dyadic": upper_endpoint,
                "relative_accuracy_bits": enclosure.rel_accuracy_bits(),
            })

    require(len(certificates) == 252, "Expected 252 nonzero entries")
    require(len(exact_zero_identities) == 250, "Expected 250 exact odd zeroes")
    return {
        "table": "T15",
        "rigour": RIGOUR,
        "status": "passed",
        "python_flint_version": flint.__version__,
        "maximum_order": MAX_ORDER,
        "working_bits": WORKING_BITS,
        "gamma_recurrence_cross_check_bits": CROSS_CHECK_BITS,
        "certificate_endpoint_bits": CERTIFICATE_BITS,
        "certified_nonzero_entries": len(certificates),
        "exact_odd_zero_entries": len(exact_zero_identities),
        "cross_checked_series_coefficients": MAX_ORDER + 1,
        "minimum_relative_accuracy_bits": minimum_accuracy,
        "maximum_radius_in_last_place_units": maximum_radius_units.str(20),
        "shifted_decimal_intervals_rejected": shifted_controls,
        "scalar_normalization_control": "passed",
        "odd_zero_proof": "xi(s)=xi(1-s), DLMF 25.4.3; not inferred from rounding",
        "primary_series_seconds": primary_seconds,
        "total_seconds": time.monotonic() - started,
        "maximum_resident_kib": resource.getrusage(resource.RUSAGE_SELF).ru_maxrss,
        "numbers_sha256": hashlib.sha256(json.dumps(
            numbers, ensure_ascii=False, separators=(",", ":")
        ).encode()).hexdigest(),
        "certificates": certificates,
        "exact_zero_identities": exact_zero_identities,
        "api_writes": False,
        "numeric_changes": False,
    }


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("table_json", type=Path)
    arguments = parser.parse_args()
    resource.setrlimit(resource.RLIMIT_AS, (768 * 1024**2, 768 * 1024**2))
    resource.setrlimit(resource.RLIMIT_CPU, (45, 46))
    document = json.loads(arguments.table_json.read_text())
    print(json.dumps(certify(document), ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
