"""Independent triangular-Weil quadrature checker for this draft.

  sage -python independent_check.py stored-document.json --output check-results.json
Uses no generator imports or Lerch/digamma/Catalan evaluation. It checks all
selected values by Suzuki's W(Delta_t) formula with a separate factorization
of each integer for von Mangoldt support. See numerical-evidence.md for the
analytic endpoint removal and independence limits. Requires Sage and numberdb.
"""
import numberdb.sage as numberdb
from sage.rings.real_arb import RealBallField
from sage.rings.complex_arb import ComplexBallField
from sage.rings.integer_ring import ZZ
from sage.rings.rational_field import QQ
import json, argparse
from decimal import Decimal

R = RealBallField(512)
C = ComplexBallField(512)
TOL = R(2)**(-420)

def finite(z):
    return bool(z.real().is_finite() and z.imag().is_finite())

def factor_prime_power(m):
    for p in range(2,m+1):
        if m % p == 0:
            n=m
            while n % p == 0: n//=p
            return p if n==1 else None
    return None

def sinhc(z):
    """Entire sinh(z)/z, including zero, with an explicit Taylor tail."""
    if not z.contains_zero():
        return z.sinh()/z
    r=abs(z)
    if not r.is_finite() or r > 16:
        return C('nan')
    total=C(1); term=C(1); bound=R(1)
    for k in range(1,2000):
        term *= z*z/((2*k)*(2*k+1))
        total += term
        bound *= r*r/((2*k)*(2*k+1))
        ratio=r*r/((2*k+2)*(2*k+3))
        if ratio < 1:
            error=bound*ratio/(1-ratio)
            if error < R(2)**(-470):
                return total.add_error(error)
    return C('nan')

def triangular(q):
    if q==1: return R(0)
    t=C(q).log()
    # W(Delta_t), Delta_t(x)=(t-|x|)_+/2.
    # For x<t, the subtracted archimedean integrand is
    # ((t-x)*exp(x/2)-t)/(exp(x)-exp(-x)).
    # Writing y=exp(x/2), cancel exp(x/2)-1 algebraically:
    # t*y^2/((y+1)*(y^2+1)) - y/(2*sinhc(x)).
    # Its limit at x=0 is t/4-1/2. For x>t the exact
    # integral is -t*atanh(exp(-t)), so no numeric tail is discarded.
    def regular(x, analytic):
        y=(x/2).exp()
        return t*y*y/((y+1)*(y*y+1))-y/(2*sinhc(x))
    J=C.integral(regular,0,t,rel_tol=TOL,abs_tol=TOL,eval_limit=300000)
    tail=-t*((1+(-t).exp())/(1-(-t).exp())).log()/2
    arithmetic=C(0)
    for m in range(2,q):
        p=factor_prime_power(m)
        if p is not None:
            arithmetic += C(p).log()/C(m).sqrt()*(t-C(m).log())
    poles=C.integral(lambda x,a: 2*(t-x)*(x/2).cosh(),0,t,
                     rel_tol=TOL,abs_tol=TOL)
    W=poles-arithmetic-t/2*(C(4)*C.pi()).log()-t*R.euler_constant()/2-J-tail
    if not finite(W) or not W.imag().contains_zero():
        raise ArithmeticError('Nonfinite or nonreal quadrature')
    return -W.real()

def decimal_interval(text):
    d=Decimal(str(text)); n,e=d.as_tuple().digits,d.as_tuple().exponent
    c=ZZ(''.join(map(str,n))) * (-1 if d.is_signed() else 1)
    unit=QQ(10)**e
    if '.' not in str(text) and 'e' not in str(text).lower():
        return QQ(c),QQ(c)
    return c*unit-unit,c*unit+unit

def accepts(value,text):
    lo,hi=decimal_interval(text)
    if lo==hi:
        return bool(value.is_exact() and value==R(lo))
    return bool(value.is_finite() and value.accuracy()>=380 and
                value>R(lo) and value<R(hi) and value.rad_as_ball()<(R(hi)-R(lo))/1000)

def records(document):
    block=document.get('Data',document.get('Numbers'))
    if isinstance(block,list):return block
    if isinstance(block,dict):
        out=[]
        for t,value in block.items():
            e=dict(value) if isinstance(value,dict) else {'number':value}
            e['params']={'t':str(t)}
            out.append(e)
        return out
    raise ValueError('Expected flat or one-parameter nested stored records')

def run(document):
    entries=records(document)
    failures=[]; comparisons=[]
    expected=['0']+['log(%d)'%q for q in range(2,257) if factor_prime_power(q)]
    observed=[str(e['params']['t']) for e in entries]
    if observed!=expected:failures.append('selection/order mismatch')
    if len(entries)!=71:failures.append('entry count is not 71')
    values={}
    for e in entries:
        t=str(e['params']['t']);q=1 if t=='0' else int(t[4:-1])
        v=triangular(q);values[t]=v
        ok=accepts(v,e['number'])
        if not ok:failures.append(t+' interval check failed')
        comparisons.append({'t':t,'number':str(e['number']),'independent_ball':str(v),
            'accuracy_bits':None if q==1 else int(v.accuracy()),'contained_in_stored_interval':ok})
    third=C.integral(lambda x,a:x*x,0,1,rel_tol=TOL,abs_tol=TOL)
    pole_t=C(4).log()
    poles=C.integral(lambda x,a:2*(pole_t-x)*(x/2).cosh(),0,pole_t,rel_tol=TOL,abs_tol=TOL)
    # Controls cover a nonzero quadrature, nonzero exact pole term, exact
    # origin, and the removable sinhc endpoint and a nonzero sinhc value.
    control=bool(finite(third) and (third-C(QQ(1)/3)).contains_zero() and
                 finite(poles) and (poles-C(2)).contains_zero() and
                 abs(third.real()-R(QQ(1)/3))<R(2)**(-390) and
                 sinhc(C(0))==1 and (sinhc(C(1))-C(1).sinh()).contains_zero() and accepts(values['0'],'0'))
    good=next(e['number'] for e in entries if e['params']['t']=='log(4)')
    bad_sign=str(good)[1:] if str(good).startswith('-') else '-'+str(good)
    wrong_factor=R(2)*values['log(4)']
    negative=bool(not accepts(values['log(4)'],bad_sign) and not accepts(wrong_factor,good)
                  and not accepts(R('nan'),good) and not accepts(values['log(4)'].add_error(1),good))
    if not control: failures.append('known-answer control failed')
    if not negative: failures.append('negative control not rejected')
    return {'checked_entries':len(entries),'total_entries':len(entries),'failures':failures,
        'known_answer_control':control,'negative_control_rejected':negative,
        'minimum_accuracy_bits':min(x['accuracy_bits'] for x in comparisons if x['accuracy_bits'] is not None),
        'method':'512-bit rigorous triangular-Weil quadrature; rel/abs tolerance 2^-420; independent factorization support',
        'controls':{'integral_x_squared':str(third),'pole_integral_t_log4':str(poles),
                    'wrong_sign_at_log4':bad_sign,'wrong_factor_rejected':not accepts(wrong_factor,good),
                    'nan_rejected':not accepts(R('nan'),good),'wide_ball_rejected':not accepts(values['log(4)'].add_error(1),good)},
        'comparisons':comparisons}

if __name__=='__main__':
    parser=argparse.ArgumentParser();parser.add_argument('document');parser.add_argument('--output',default='check-results.json');a=parser.parse_args()
    with open(a.document) as f: d=json.load(f)
    report=run(d)
    with open(a.output,'w') as f:json.dump(report,f,indent=2)
    print(json.dumps({k:v for k,v in report.items() if k!='comparisons'},indent=2))
    raise SystemExit(bool(report['failures']))
