"""Check van Hoeij's rounding formula against the public OEIS A000159 table.

Requires python-flint. Save https://oeis.org/A000159/b000159.txt locally
and run: python3 verify_bessel_table.py b000159.txt
"""

import argparse
from pathlib import Path

from flint import arb, ctx


def read_counts(path):
    counts = {}
    for line in path.read_text(encoding="utf-8").splitlines():
        row = line.partition("#")[0].strip()
        if row:
            index, count = map(int, row.split())
            counts[index] = count
    return counts


def verify(counts):
    ctx.prec = 2304
    two = arb(2)
    bessel = [two.bessel_k(0), two.bessel_k(1)]
    for order in range(1, 249):
        bessel.append(order * bessel[-1] + bessel[-2])

    half = arb(1) / 2
    scale = 4 * arb(-2).exp()
    for n in range(11, 251):
        terms = (n + 3*half) * bessel[n - 1] - (n - 9*half) * bessel[n - 2]
        predicted = (two*n / 3) * (scale * terms + (-1)**n)
        nearest = counts[n] + int(n == 11)
        if not abs(predicted - nearest) < half:
            raise ArithmeticError(f"Rounding not certified at n={n}")
        if n in (11, 12):
            print(f"n={n}, formula={predicted.str(22)}, seating count={counts[n]}")
    print("Arb certified the one-count discrepancy at 11 and all 239 matches from 12 through 250.")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("table", type=Path, help="OEIS A000159 two-column integer table")
    verify(read_counts(parser.parse_args().table))
