"""External review. Evaluate the paper inputs using Python's standard library."""
import json
import re
import sys
from decimal import Decimal as D, getcontext
from fractions import Fraction
from pathlib import Path

getcontext().prec = 65
root = Path(sys.argv[1])

def atan_series(x):
    term = x
    total = x
    n = 1
    while abs(term) > D('1e-68'):
        term *= -x*x
        total += term/(2*n+1)
        n += 1
    return total

def bisect(f, lo, hi):
    for _ in range(207):
        mid = (lo+hi)/2
        if f(mid)>0:
            hi=mid
        else:
            lo=mid
    return (hi+lo)/2

pi = 16*atan_series(D(1)/5) - 4*atan_series(D(1)/239)
tip = bisect(lambda v: ((pi*v).exp()-(-pi*v).exp())/2-1,D(0),D(1))
lam = 1/(D(1)/12 + tip**2/3)
# Independent count from the spherical harmonics in section 2.1,
# including Weyl multiplicities and transverse vector polarizations.
def letters(y, fermion_sign=1):
    x = y*y
    return sum(6*(k+1)**2*x**(k+1) + fermion_sign*8*(k+1)*(k+2)*y**(2*k+3)
               + 2*(k+1)*(k+3)*x**(k+2) for k in range(65))

y = bisect(lambda q: letters(q)-1,D('.2'),D('.4'))
assert abs(y-(2-D(3).sqrt())) < D('1e-55')
beta = -2*y.ln()
btext=next((root/'sources').rglob('B_series.tex')).read_text()
coefs=re.findall(r'^\s*(\d+)\s*&\s*\$([-\d./]+)\$',btext,re.M)
pieces=[{},{}]
for i,(power,coef) in enumerate(coefs):
    r=Fraction(coef)
    pieces[0 if i<11 else 1][int(power)] = D(r.numerator)/D(r.denominator)
assert [len(p) for p in pieces]==[11,7]
sums=[sum(v*y**n for n,v in p.items()) for p in pieces]
c3,Q4=map(D,('0.16821','2.1222'))
A2=1-letters(y*y,fermion_sign=-1)
I=Q4/2+2*c3*c3/A2
q=D('-2.234')
b=(-4*beta**2*I+beta*q)/(256*pi**4)
tab=(root/'sources/bootstrap.tex').read_text().split(r'\subsection{The slope, and why earlier fits gave 9.08}')[1].split(r'\label{tab:2}')[0]
pts=[(int(c),D(g)) for c,g in re.findall(r'^\s*(\d+)\s*&\s*[\d.]+\s*&\s*([\d.]+)\s*&',tab,re.M)]
assert len(pts)==24 and pts[-1][0]==2048
endpoint=[{'c':c,'gap_input':g,'denominator':c/g,'distance_to_limit':lam-c/g,'scaled_correction':(g-c/lam)/D(c)**(D(1)/3)} for c,g in [pts[0],pts[-1]]]
# In the general-slit Poisson representation, integration by parts eliminates
# the near-cancellation at infinity. For a = pi*s, sigma = sinh(a),
# J = cosh(a)*int_0^1 dt/((1+t)*sqrt(t*t+sigma*sigma))
#   = a - log(sigma), by t = sigma*sinh(u), v = tanh(u/2).
# Only the tip coefficient of this Dirichlet problem is checked here.
def tip_coefficient(position):
    a = pi * position
    sh = (a.exp() - (-a).exp()) / 2
    ch = (a.exp() + (-a).exp()) / 2
    return 4*(2*pi*sh/ch).sqrt()*sh.ln()/(3*pi)

def order_two_gap(c):
    # At P=2 only odd Laguerre polynomials of degrees 1 and 3 occur.
    # Enforce vanishing vacuum action, then bracket the last simple zero
    # using the larger stationary point of the resulting cubic.
    a = D(c-1)/12
    def L1(x):
        return 1-x
    def L3(x):
        return 1-3*x+3*x*x/2-x**3/6
    def vac(L):
        return sum(D(factor)*(-2*pi*j).exp()*L(4*pi*(j-a))
                   for j,factor in enumerate((1,-2,1)))
    k = vac(L3)/vac(L1)
    def poly(x):
        return k*L1(x)-L3(x)
    turning = 3+(3+2*k).sqrt()
    upper = 2*turning
    while poly(upper)<0:
        upper *= 2
    assert poly(turning)<0
    return a+bisect(poly,turning,upper)/(4*pi)

low_order = {str(c):order_two_gap(c) for c in (4,12,24,48,64,128,256,512,2048)}
samples = {str(s):tip_coefficient(s) for s in map(D, ['0.24','0.275','0.285','0.32'])}
assert abs(tip_coefficient(tip))<D('1e-58')
print(json.dumps({'finite_order_P2_gap':low_order,'slit_tip_coefficients':samples,'description':'Independent arithmetic review using the version-1 source tables. The microscopic kernel coefficients and finite-c gap values are paper inputs.','lambda_v':lam,'band_tip':tip,'Hagedorn_free_TR':1/beta,'Hagedorn_beta_over_R':beta,'y_H':y,'appendix_B_truncated':sums,'I_from_published_inputs':I,'sign_change_q4':4*beta*I,'b_over_lambda_squared_from_published_inputs':b,'leading_relative_coexistence_window_over_lambda_squared':-b/(6*beta),'finite_c_rows':len(pts),'finite_c_endpoints':endpoint},default=str,indent=2))
