"""Verify the link-specific numerical comparison for numberdb.org/T487.

Run with SageMath and the numberdb client installed:
    cat /path/to/api-key | sage -python check_t487_repair.py
The key is needed while T487 is private. This script only reads the API.
It does not repeat the full generator's certification of all 480 entries.
"""
import json
import sys
import numberdb.sage as numberdb
from sage.rings.rational_field import QQ
from sage.rings.real_arb import RealBallField
from sage.rings.complex_arb import ComplexBallField
from sage.env import SAGE_VERSION

numberdb.configure(api_key=sys.stdin.read().strip())
source = numberdb.table('T487')
slug = 'Dirichlet_eigenvalues_of_the_classical_planar_domains'
target = numberdb.table(slug)


def decimal_interval(text):
    whole, frac = str(text).split('.')
    center = QQ(int(whole + frac)) / QQ(10) ** len(frac)
    unit = QQ(1) / QQ(10) ** len(frac)
    return center - unit, center + unit


def cross_product(order, ratio, x):
    C = ComplexBallField(896)
    z, n, ratio = C(x), C(order), C(ratio)
    value = z.bessel_J(n) * (ratio*z).bessel_Y(n) - z.bessel_Y(n) * (ratio*z).bessel_J(n)
    assert value.real().is_finite() and value.imag().is_finite()
    assert value.imag().contains_zero()
    return value.real()


R = RealBallField(896)
# Known nonzero control: the order 1/2 cross-product is elementary.
x = R(QQ(1)/3)
observed = cross_product(R(QQ(1)/2), R(2), x)
expected = 2*((2-1)*x).sin()/(R.pi()*R(2).sqrt()*x)
assert observed.is_finite() and expected.is_finite()
assert observed > 0 and expected > 0
assert R(observed.rad()) < R(10)**(-250) and R(expected.rad()) < R(10)**(-250)
assert (observed-expected).contains_zero()

root_text = source['Numbers']['0']['2']['1']
eigenvalue_text = target['Numbers']['annulus-1-2']['1']
lo, hi = decimal_interval(root_text)
elo, ehi = decimal_interval(eigenvalue_text)
left, right = cross_product(R(0), R(2), R(lo)), cross_product(R(0), R(2), R(hi))
assert left.is_finite() and right.is_finite()
assert left > 0 and right < 0
assert lo > 0 and elo <= lo**2 < hi**2 <= ehi
print(json.dumps({
    'sage_version': SAGE_VERSION,
    'arb_precision_bits': 896,
    'half_integer_nonzero_control': 'passed',
    'source_entry': 'T487#0,2,1',
    'source_number': root_text,
    'target_entry': slug+'#annulus-1-2,1',
    'target_number': eigenvalue_text,
    'source_interval_endpoint_signs': ['positive', 'negative'],
    'squared_source_interval_inside_target_interval': True,
    'scope': 'The linked annulus comparison only; no new certification of the full table.'
}, indent=2))
