"""Recheck the height-92 bounds in the accompanying audit using mpmath 1.3.0."""

from math import isqrt
from mpmath import iv

iv.dps = 50
real = iv.mpf
exp, log, sqrt, pi = iv.exp, iv.log, iv.sqrt, iv.pi


def upper(name, value, bound):
    if not (value < real(bound)):
        raise ArithmeticError(f"{name}: {value} exceeds {bound}")
    print(f"{name}: {value} < {bound}")


def lower(name, value, bound):
    if not (value > real(bound)):
        raise ArithmeticError(f"{name}: {value} is below {bound}")
    print(f"{name}: {value} > {bound}")


cut = 10_000
prime_sum = real(0)
for p in range(5, cut + 1):
    if all(p % d for d in range(2, isqrt(p) + 1)):
        prime_sum += log(p) / (p*p - 1)
prime_sum += (1 + log(cut)) / (cut * (1 - real(1)/cut**2))
budget = log(sqrt(108)/(2*pi)) + 1 - iv.euler + 2*prime_sum
upper("Hadamard budget", budget, "1.331")
upper("Budget ceiling below the weight of a double central zero", real("1.331"), real(4)/3)

first = real("2.82")
low = real("1.35")*(first**2 + real("2.25"))/real("1.5") * sqrt(2*pi)*exp(-pi*first/2)
upper("zeros through height 92, normalized", low, "0.2754")

height = real(92)
gamma = sqrt((1 + 1/height**2) * 2*pi*height / (1 - exp(-2*pi*height))) * exp(-pi*height/2)
high_coefficient = real("1.35")*(4 + height**2)*gamma
upper("high zeros before the factor X^B", high_coefficient, "4.77e-58")

xmin = real("1e50")
square_start = real("1e16")
slope = real("0.4999")
lower("slope beyond square_start", real("0.5") - 3/(840*log(square_start))
      - 2*log(2)/square_start, slope)
upper("loss below square_start", (log(square_start)+slope)*square_start+2*log(2), "4e17")
squares = slope*sqrt(pi)/2 - real("4e17")/sqrt(xmin)
lower("normalized square term", squares, "0.4430")

alpha = real(3)/8
s = 3*alpha
integral = real(3)**(1-s)*(log(3)/(s-1) + 1/(s-1)**2)
higher = 2/(1-real(2)**(-alpha))*(log(2)/real(2)**s + log(3)/real(3)**s + integral)
higher *= xmin**(alpha-real("0.5"))
upper("normalized higher prime powers", higher, "0.0010")
lower("favorable residue at zero", log(xmin)-log(sqrt(108)/(2*pi))-2*real("1.35"), "0")
contour = real(100)/xmin

for beta, exponent, tail_limit, margin in [
    (real(1), 110, "0.006", "0.16362"),
    (real(7)/8, 147, "0.008", "0.16203"),
]:
    tail = high_coefficient * real(10)**(exponent*(beta-real("0.5")))
    upper(f"normalized high zeros to 10^{exponent}", tail, tail_limit)
    lower(f"margin to 10^{exponent}, using unrounded bounds", squares-low-tail-higher-contour, margin)
