"""Check the three- and four-adjacency proofs with the Python standard library.

Run with Python 3.9 or later. An optional --oeis-table argument accepts a local
copy of https://oeis.org/A000181/b000181.txt for an independent comparison.
"""

import argparse
from fractions import Fraction
from functools import lru_cache
from itertools import permutations
from math import comb, factorial, prod
from pathlib import Path


def bridge_coefficients(r, n):
    """Coefficients of v(n), v(n-1), and (-1)**n in u(n,r)/n."""
    den = n * (n - 1)
    return (
        (1, 0, 0),
        (2, 2, Fraction(4, den)),
        (4, 5 - 2*n, Fraction(-2*(n - 4), den)),
        (Fraction(2*(9 - 2*n), 3), Fraction(2*(2*n**2 - 9*n + 12), 3),
         Fraction(2*(n - 6)*(n - 3), 3*den)),
    )[r]


def verify_bridge():
    """Verify the three rows by induction from the Kaplansky-Riordan identities."""
    for r, base in enumerate((2, 8, 4, 8)):
        a, b, c = bridge_coefficients(r, 4)
        if 4 * (a*Fraction(2, 4) + b*Fraction(1, 3) + c) != base:
            raise ArithmeticError(f"Wrong bridge initial value for r={r}")

    # After clearing n(n-1)(n-2), the last coordinate has degree at most 4.
    # The first two are already polynomials of degree at most 3.
    for n in range(5, 13):
        for r in (1, 2, 3):
            a, b, c = bridge_coefficients(r, n)
            previous = bridge_coefficients(r, n - 1)
            previous_lower = bridge_coefficients(r - 1, n - 1)
            weight = Fraction(2*n - r - 1, r)
            left = ((n - 1)*a + b, a, c - Fraction(4, n*(n - 2))*a)
            x, y, z = (v + weight*w for v, w in zip(previous, previous_lower))
            if left != (x, y, -z):
                raise ArithmeticError(f"Bridge identity fails for r={r}, n={n}")


def three_coefficients(n):
    return (
        2*(-252307*n + 1041077),
        504614*n**2 - 3362985*n + 5118150,
        1280831*n**2 - 7397886*n + 6461565,
        746598*n**2 - 2913543*n - 1336090,
        -405481*n**2 + 6175011*n - 15469320,
        -375862*n**2 + 4098537*n - 8846430,
        2*(-187931*n + 560630),
    )


def verify_three_recurrence():
    # The bridge starts at 4. The first recurrence uses u(3,3) as well.
    first = (2, 8, 20, 152, 994, 7888, 70152)
    if sum(q*value for q, value in zip(three_coefficients(9), reversed(first))) != 0:
        raise ArithmeticError("Three-hit recurrence fails at n=9")

    # Use the basis (v_m, v_(m-1), (-1)^m) at m=n-6. After multiplying
    # by the product of m+s for -1 <= s <= 6, each residual has degree <= 19.
    for m in range(4, 24):
        previous, current = (0, 1, 0), (1, 0, 0)
        three_hits = []
        for i in range(7):
            n = m + i
            sign = (-1)**i
            a, b, c = bridge_coefficients(3, n)
            row = [n*(a*x + b*y) for x, y in zip(current, previous)]
            row[2] += n*c*sign
            three_hits.append(row)
            if i < 6:
                following = [n*x + y for x, y in zip(current, previous)]
                following[2] += Fraction(4*sign, n*n - 1)
                previous, current = current, following
        weights = three_coefficients(m + 6)
        for coordinate in zip(*reversed(three_hits)):
            if sum(q*v for q, v in zip(weights, coordinate)) != 0:
                raise ArithmeticError(f"Three-hit recurrence fails at m={m}")


def seed_at_eight():
    """Enclose (-1)^8 (u(8,0)/8 - 2 exp(-2) K_8(2)) by rational arithmetic."""
    def exp_partial(last):
        return sum(Fraction((-2)**k, factorial(k)) for k in range(last + 1))

    series = sum(Fraction((-1)**m * factorial(7 - m), factorial(m)) for m in range(8))
    # Wyman-Moser (3.21), scaled by exp(-2)/8, gives error <= 1/(e*7!).
    radius = Fraction(1, 2*factorial(7))
    center = Fraction(4738, 8)
    lo = center - exp_partial(18)*series - radius
    hi = center - exp_partial(17)*series + radius
    outer = (-Fraction(1, 100), -Fraction(1, 125))
    if not outer[0] < lo <= hi < outer[1]:
        raise ArithmeticError("Wyman-Moser seed enclosure fails")
    return outer


@lru_cache(maxsize=None)
def zero_hit_error(j, depth):
    if j == 8:
        return seed_at_eight()
    if depth == 0:
        return -Fraction(1, 2*j), Fraction(1, 2*j)
    left_lo, left_hi = zero_hit_error(j - 1, depth - 1)
    right_lo, right_hi = zero_hit_error(j + 1, depth - 1)
    shift = Fraction(4, j*j - 1)
    return (left_lo - right_hi - shift)/j, (left_hi - right_lo - shift)/j


def three_hit_error(n):
    """Interval for (-1)^n times (integer count minus proposed Bessel value)."""
    lo1, hi1 = zero_hit_error(n - 1, 5)
    lo2, hi2 = zero_hit_error(n - 2, 5)
    c1 = Fraction(4*n, 3) * (n + Fraction(3, 2))
    c2 = Fraction(4*n, 3) * (n - Fraction(9, 2))
    offset = Fraction(20*n, 3*(n - 1)*(n - 2))
    return -c1*hi1 - c2*hi2 - offset, -c1*lo1 - c2*lo2 - offset


def verify_rounding():
    endpoints = [(11, Fraction(543, 1000), Fraction(573, 1000)),
                 (12, Fraction(479, 1000), Fraction(488, 1000))]
    for n, lower, upper in endpoints:
        lo, hi = three_hit_error(n)
        if not lower < lo <= hi < upper:
            raise ArithmeticError(f"Endpoint enclosure fails at n={n}")
    for n in range(12, 64):
        lo, hi = three_hit_error(n)
        if not 0 < lo <= hi < Fraction(488, 1000):
            raise ArithmeticError(f"Three-hit rounding fails at n={n}")

    # For n >= 64 the analytic upper bound is decreasing in x = n-3 >= 61.
    x = 61
    tail = Fraction(28, x) + Fraction(116, x*x) + Fraction(96, x**3)
    if tail >= Fraction(1, 2):
        raise ArithmeticError("Uniform tail bound fails at its maximum")
    print("Three adjacent couples: the Bessel formula rounds correctly for every n >= 12.")
    print("At n=11 the signed error is between 0.543 and 0.573, certifying a wrong rounding.")


def coefficients(n):
    """Mathar's coefficients, ordered from a(n) through a(n - 4)."""
    return (
        3 * (2111*n - 8303) * (n - 4) * (2*n - 9)**2,
        -(n - 3) * (25332*n**4 - 377236*n**3 + 1898681*n**2 - 3320738*n + 484000),
        -2 * (n - 4) * (12140*n**4 - 118152*n**3 + 337063*n**2 - 377436*n + 225720),
        1052*n**5 - 40656*n**4 + 266063*n**3 - 549153*n**2 + 49850*n + 655200,
        (263*n + 640) * (n - 3) * (2*n - 7)**2,
    )


def falling(value, length):
    return prod(value - i for i in range(length))


def certificate(n, m):
    common = -4 * (n - 4) * (n - 3) * (2*n - 9) * (2*n - 7)
    slope = 10 * (n - 2) * (607*n - 220)
    intercept = 6596*n**3 - 42863*n**2 + 62785*n + 17600
    return common * (slope*m + intercept)


def verify_polynomial_identity():
    """Check the four-adjacency identity after clearing denominators.

    The residual has degree at most 10 in n and 4 in m. At each of five
    distinct m it vanishes identically in n by the eleven evaluations. The
    five roots in m then prove the identity for every n and m.
    """
    for n in range(8, 19):
        for m in range(5):
            lhs = sum(
                (-1)**j * q * (n - j) * falling(n - m - 4, j)
                * falling(n + m - 1 - j, 4 - j)
                for j, q in enumerate(coefficients(n))
            )
            rhs_twice = (
                -(n - m - 4) * (n + m - 4) * (m + 1) * certificate(n, m + 1)
                - 2*m * (2*m - 1) * certificate(n, m)
            )
            if 2*lhs != rhs_twice:
                raise ArithmeticError(f"Polynomial identity fails at n={n}, m={m}")


def count_four(n):
    """Coefficient of t^4 from the cycle matching count."""
    twice_count = (-1)**n * n * sum(
        (-1)**m * factorial(m) * comb(2*m + 3, 3) * comb(n + m - 1, 2*m + 3)
        for m in range(n - 3)
    )
    value, remainder = divmod(twice_count, 2)
    if remainder:
        raise ArithmeticError(f"Nonintegral count at n={n}")
    return value


def enumerate_seatings(n):
    total = 0
    for order in permutations(range(n)):
        hits = sum(
            partner == gap or partner == (gap + 1) % n
            for gap, partner in enumerate(order)
        )
        total += hits == 4
    return total


def check_examples(table_path):
    values = {n: count_four(n) for n in range(4, 251)}
    for n in range(4, 10):
        if enumerate_seatings(n) != values[n]:
            raise ArithmeticError(f"Direct seating count disagrees at n={n}")
    for n in range(8, 251):
        residual = sum(q * values[n - j] for j, q in enumerate(coefficients(n)))
        if residual:
            raise ArithmeticError(f"Recurrence fails at n={n}")
    for p in (5, 7, 11, 13, 17, 19, 23, 29, 31):
        for n in range(4, 251 - 2*p):
            if (values[n] + 2*values[n + p] + values[n + 2*p]) % p:
                raise ArithmeticError(f"Congruence fails at p={p}, n={n}")
    print("Direct enumeration agrees for n=4..9. Initial counts are",
          ", ".join(str(values[n]) for n in range(4, 10)) + ".")
    print("The counts through n=250 satisfy the recurrence and the tested congruences.")
    if table_path is not None:
        published = {}
        for line in table_path.read_text(encoding="utf-8").splitlines():
            line = line.partition("#")[0].strip()
            if line:
                index, value = map(int, line.split())
                published[index] = value
        for n, value in values.items():
            if published.get(n) != value:
                raise ValueError(f"Missing or differing published value at n={n}")
        print("All 247 entries for n=4..250 match the supplied OEIS table.")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--oeis-table", type=Path, help="local A000181 two-column table")
    args = parser.parse_args()
    verify_bridge()
    verify_three_recurrence()
    verify_rounding()
    verify_polynomial_identity()
    print("The degree-bounded polynomial certificate vanishes identically.")
    check_examples(args.oeis_table)
