#!/usr/bin/env python3
"""Rigorous central-derivative enclosure from interval Riemann sums + tails.
No PARI derivative or L-value is used as input to the certificate.
"""
from pathlib import Path
import json,time
from flint import arb,ctx
ROOT=Path(__file__).resolve().parent
ctx.prec=192
first=json.loads((ROOT/'q8-results.json').read_text())['fields'][0]
classic=json.loads((ROOT/'q8-magma-results.json').read_text())
fields=[dict(label=first['label'],Q=48,nu=1,M=1000,a=first['coefficients_first_2000']),
        dict(label=classic['label'],Q=205,nu=0,M=1500,a=classic['certificate']['coefficients'])]
result=dict(method='Interval Riemann sums of the theta Mellin derivative, monotone K0 endpoint hulls, explicit two tails',arb_bits=ctx.prec,fields=[])
def S2(r,m):return r**m*(m*m/(1-r)+2*m*r/(1-r)**2+r*(1+r)/(1-r)**3)
for f in fields:
    started=time.monotonic();Q=f['Q'];nu=f['nu'];M=f['M'];c=2*arb.pi()/Q;T=512
    terms=[(n,f['a'][n-1]*n**nu) for n in range(1,M+1) if f['a'][n-1]]
    C=8*arb(Q)**(-nu)*(arb.pi()/(2*c)).sqrt()
    ntail=C*(1/c+1/c**2)*S2((-c).exp(),M+1)
    rt=(-c*T).exp();ttail=C*(arb(T)/c+1/c**2)*rt*(1+rt)/(1-rt)**3
    completion=arb(Q).sqrt()*arb.pi()**(-arb(1)/2-nu)*(arb(1)/4+arb(nu)/2).gamma()**2
    attempts=[]
    for steps in [64,128]:
        I=arb(0);left=None
        for band in range(9):
            for k in range(steps):
                a=arb(2)**band*(1+arb(k)/steps)
                b=arb(2)**band*(1+arb(k+1)/steps)
                if left is None:left=[(c*n*a).bessel_k(0) for n,an in terms]
                right=[(c*n*b).bessel_k(0) for n,an in terms]
                x=a.union(b)
                theta=arb(0)
                for (n,an),ka,kb in zip(terms,left,right):theta+=an*ka.union(kb)
                theta*=4*(x/Q)**nu
                I+=2*theta*x**(-arb(1)/2)*x.log()*(b-a)
                left=right
        enclosure=(I+arb(0,(ntail+ttail).upper()))/completion
        attempts.append(dict(cells_per_dyadic_band=steps,cells=steps*9,finite_completed_derivative=I.str(60,more=True),Lprime_enclosure=enclosure.str(60,more=True)))
        print(f['label'],steps*9,'cells: Lprime in',enclosure,flush=True)
        if enclosure>0:break
    assert enclosure>0,'Refinement did not exclude zero'
    # Convenient outward-rounded rational interval, checked against the full ball.
    low=int(float(enclosure.lower())*100)/100
    high=(int(float(enclosure.upper())*100)+1)/100
    while not enclosure>arb(str(low)):low-=.01
    while not enclosure<arb(str(high)):high+=.01
    assert enclosure>arb(str(round(low,2))) and enclosure<arb(str(round(high,2)))
    serialized=arb(enclosure.str(60,more=True))
    assert serialized>arb(str(round(low,2))) and serialized<arb(str(round(high,2)))
    result['fields'].append(dict(label=f['label'],Q=Q,gamma_shift=nu,coefficient_cutoff=M,
              t_cutoff=T,completed_coefficient_tail=str(ntail),completed_integral_tail=str(ttail),
              positive_completion=str(completion),attempts=attempts,
              Lprime_enclosure=enclosure.str(60,more=True),coarse_interval=[round(low,2),round(high,2)],
              excludes_zero=True,central_multiplicity=1,elapsed_seconds=time.monotonic()-started))
(ROOT/'q8-simplicity-results.json').write_text(json.dumps(result,indent=2)+'\n')
print('PASS: both negative-sign central zeros are simple, by interval derivative certificates',flush=True)
