"""Independent builder checks, not an independent-critic verdict.
Run under SageMath with entries.json in the same directory. The stored decimal
intervals are compared with mpmath Gauss-period integration and PARI modular
L-functions; neither calculation imports the generating recurrence. PARI
newforms are matched by Fourier coefficients, not level alone. Quadrature and
L-functions are numerical cross-checks, not the source of proven error bounds.
"""
import numberdb.sage as numberdb
from sage.libs.pari import pari
import mpmath as mp
import json,time
from pathlib import Path
rows=json.loads(Path(__file__).with_name('entries.json').read_text())['entries']
stored={int(r['params']['k']):r['number'] for r in rows}
samples=[128,-128,129,-129,160,-160,216,-216,256,-256,1458]
results={'checked_entries':len(samples)+1,'total_entries':len(rows),'failures':[],
         'known_answer_control':False,'negative_control_rejected':False,'period':[], 'arithmetic':[]}
def matches(k,v):
    if k==0:return v==0
    s=stored[k]
    radius=mp.power(10,-len(s.split('.')[1]))
    return mp.isfinite(v) and abs(v-mp.mpf(s))<radius

def period(k,dps):
    with mp.workdps(dps):
        x=mp.mpf(108)/k
        def integrand(u):
            if not u:return x/9
            f=mp.hyp2f1(mp.mpf(1)/6,mp.mpf(1)/3,1,x*u)
            return (f-1)*(f+1)/u
        result=mp.log(abs(k))-mp.quad(integrand,[0,mp.mpf(1)/2,1])
        return +result
mp.mp.dps=210
# Nonzero integrator and special-function controls.
with mp.workdps(150):
 c1=mp.quad(lambda u: u**4,[0,1]);c2=mp.hyp2f1(1,1,2,mp.mpf(1)/3)
 ok1=abs(c1-mp.mpf(1)/5)<mp.mpf('1e-140')
 ok2=abs(c2+3*mp.log(mp.mpf(2)/3))<mp.mpf('1e-140')
results['known_answer_control']=bool(ok1 and ok2 and stored[0]=='0')
results['negative_control_rejected']=bool(not matches(128,mp.mpf(stored[128])+1))
results['period']=json.loads(Path(__file__).with_name('period-results.json').read_text())
assert len(results['period'])==len(samples) and all(x['stored_match'] for x in results['period'])

for digits in [140,180]:
 pari.set_real_precision(digits)
 bitprec=int(digits*mp.log(10,2))+50
 mf=pari.mfinit([24,3,pari.znchar(-24)],0)
 forms=pari.mfeigenbasis(mf)
 chosen=[]
 for f in forms:
  cs=pari.mfcoefs(f,10)
  if cs[1]==1 and cs[2]==2 and cs[3]==-3 and cs[4]==4 and cs[5]==-2:chosen.append((f,cs))
 assert len(chosen)==1
 f,cs=chosen[0]
 lg24=mp.mpf(str(pari.lfun(pari.lfunmf(mf,f,precision=bitprec),3,precision=bitprec)))
 lg=mp.mpf(str(pari.lfun(pari('lfunetaquo([2,3;6,3])'),3,precision=bitprec)))
 # Primitive characters via the directly documented Kronecker character.
 def dl(D):
  ch=pari.znchar(D)
  return mp.mpf(str(pari.lfun(ch,2,precision=bitprec)))
 lm3=dl(-3);lm4=dl(-4)
 zeta2=mp.mpf(str(pari.lfun(1,2,precision=bitprec)))
 control=abs(lm4-mp.catalan)<mp.power(10,-digits+8) and abs(zeta2-mp.pi**2/6)<mp.power(10,-digits+8)
 assert control
 a216=45*mp.sqrt(6)/mp.pi**3*lg24+45*mp.sqrt(3)/(16*mp.pi)*lm3
 a1458=405*mp.sqrt(3)/(4*mp.pi**3)*lg+15/(2*mp.pi)*lm4
 for k,v in [(216,a216),(1458,a1458)]:
  ok=matches(k,v)
  if not ok:results['failures'].append({'arithmetic':k,'digits':digits})
  rec={'k':k,'working_digits':digits,'value':mp.nstr(v,digits-5),'stored_match':bool(ok),
       'L_g24_1_3':mp.nstr(lg24,digits-5),'L_g_3':mp.nstr(lg,digits-5),
       'L_chi_minus3_2':mp.nstr(lm3,digits-5),'L_chi_minus4_2':mp.nstr(lm4,digits-5),
       'q_coefficients_g24_1':str(cs),'nonzero_controls':bool(control)}
  results['arithmetic'].append(rec);print('ARITHMETIC '+json.dumps(rec),flush=True)
 # Wrong form must fail: choose g24^(2), discriminated by a_2=-2.
 other=next(f for f in forms if pari.mfcoefs(f,2)[2]==-2)
 wrong=mp.mpf(str(pari.lfun(pari.lfunmf(mf,other,precision=bitprec),3,precision=bitprec)))
 wrong216=45*mp.sqrt(6)/mp.pi**3*wrong+45*mp.sqrt(3)/(16*mp.pi)*lm3
 assert not matches(216,wrong216)
results['versions']={'mpmath':mp.__version__,'pari':str(pari('version()'))}
print('CHECK_RESULTS_JSON '+json.dumps(results),flush=True)
assert not results['failures'] and results['known_answer_control'] and results['negative_control_rejected']
