"""T744 numerical checks from the original monic cubic, not a review verdict.

Run sage -python independent_check.py with entries.json beside it.
No generator functions or sibling values are used. Cardano computes all three
y roots of R_k at x=exp(i*theta); Jensen integrates the sum of positive log
moduli. All unit-torus contacts are derived by the symbolic resultant below.
A cubic endpoint substitution differs from the primary sine-squared map.
The k=0 entry is also evaluated directly from the original cubic. At k=3, a
Bloch-Wigner dilogarithm formula and a Hurwitz-zeta character sum give a
separate known nonzero control. Both Jensen and mpmath are shared assumptions.
This is a builder check, not the independent actor's scientific verdict.
"""
import sys,json,time,math
from pathlib import Path
import numberdb.sage as numberdb
from sage.rings.rational_field import QQ
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
from mpmath import mp


def exact_input(text):
    if text=='16/(3*sqrt(3))':return 16/(3*mp.sqrt(3))
    if text.startswith('sqrt('):return mp.sqrt(int(text[5:-1]))
    return mp.mpf(text)


def cubic_roots(p,q):
    if p==0 and q==0:return [mp.mpc(0)]*3
    d=mp.sqrt((q/2)**2+(p/3)**3)
    choices=[-q/2+d,-q/2-d]
    u=max(choices,key=abs)**(mp.mpf(1)/3)
    v=-p/(3*u);omega=mp.exp(2*mp.pi*mp.j/3)
    return [u+v,u*omega+v/omega,u/omega+v*omega]


def direct_measure(k):
    # Res_y(R, x^3*y^3 R(1/x,1/y)) /(k*x^4) has two factors.
    # On |x|=1, with s=x+x^-1, these reduce to
    # 2*s^2-2*k*s+k^2-4 and s^3-4*s+k.
    points=[mp.mpf(0),mp.pi]
    if k*k<=8:
        for s in [(k+mp.sqrt(max(mp.mpf(0),8-k*k)))/2,(k-mp.sqrt(max(mp.mpf(0),8-k*k)))/2]:
            if -2<s<2:points.append(mp.acos(s/2))
    kap=16/(3*mp.sqrt(3))
    if k<=kap:
        alpha=mp.asin(min(1,k/kap))/3
        # s=2*t, t^3-t+k/8=0: include all real roots.
        for s in [4/mp.sqrt(3)*mp.sin(alpha),4/mp.sqrt(3)*mp.sin(mp.pi/3-alpha),-4/mp.sqrt(3)*mp.sin(mp.pi/3+alpha)]:
            if -2<s<2:points.append(mp.acos(s/2))
    cuts=sorted(set(points))
    def f(theta):
        x=mp.exp(mp.j*theta);p=k*x-1;q=x**3-x
        return sum(mp.log(max(mp.mpf(1),abs(z))) for z in cubic_roots(p,q))
    total=mp.mpf(0)
    for left,right in zip(cuts,cuts[1:]):
        if right-left<mp.eps*100:continue
        def h(t):
            if t==0 or t==1:return mp.mpf(0)
            u=t*t*(3-2*t)
            return f(left+(right-left)*u)*(right-left)*6*t*(1-t)
        total+=mp.quad(h,[0,mp.mpf('0.5'),1])
    return total/mp.pi


def bloch_wigner(z):
    return mp.im(mp.polylog(2,z))+mp.arg(1-z)*mp.log(abs(z))


def known_r3():
    # m(1+x+y)=3*sqrt(3)/(4*pi)*L(2,chi_-3).
    L=(mp.zeta(2,mp.mpf(1)/3)-mp.zeta(2,mp.mpf(2)/3))/9
    linear=3*mp.sqrt(3)*L/(4*mp.pi)
    t=(1-mp.j*mp.sqrt(5+2*mp.sqrt(13)))/2
    zeta=mp.exp(mp.j*mp.pi/3)
    conic=(bloch_wigner((t+1)/3)-2*bloch_wigner((t+1)/(zeta+1))-2*bloch_wigner((t+1)/(1/zeta+1)))/mp.pi
    return linear+conic


def symbolic():
    S=PolynomialRing(QQ,names=('x','y','k'));x,y,k=S.gens()
    R=x**3+y**3-x-y+k*x*y
    assert R(k=-k)==-R(x=-x,y=-y)
    assert R(k=3)==(x+y-1)*(x*x-x*y+y*y+x+y)
    assert R(k=0)==(x+y)*(x*x-x*y+y*y-1)
    assert -y**3*R(x=x/y,y=1/(x*y))==(x+1/x)*y*y-k*y-(x**3+1/x**3)
    reverse=x**3+(1-x*x)*y**3+(k*x*x-x**3)*y*y
    assert R.resultant(reverse,y)==k*x**4*(2*x**4-2*x**3*k+x*x*k*k-2*x*k+2)*(x**6-x**4+k*x**3-x*x+1)
    # Generic integral elliptic model discriminant.
    a=k*k-24;b=-16*(k*k-9)
    assert 16*b*b*(a*a-4*b)==4096*k*k*(k*k-9)**2*(k*k+16)
    return True


def compare(record,value):
    center=mp.mpf(record['number']);last=mp.power(10,mp.floor(mp.log10(abs(center)))-99)
    return bool(mp.isfinite(value) and abs(value-center)<=last),abs(value-center)/last


def run(path='entries.json'):
    records=json.loads(Path(path).read_text());rows=[];failures=[]
    symbolic();print('SYMBOLIC passed',flush=True)
    with mp.workdps(135):
        control=known_r3();r3=next(r for r in records if r['params']['k']=='3');known=compare(r3,control)[0]
        print('KNOWN '+json.dumps({'r3':mp.nstr(control,130),'pass':known}),flush=True)
        for record in records:
            t=time.time();k=exact_input(record['params']['k'])
            value=direct_measure(k)
            ok,ulps=compare(record,value)
            row={'k':record['params']['k'],'value':mp.nstr(value,130),'ulps':mp.nstr(ulps,12),'pass':ok,'seconds':time.time()-t}
            rows.append(row)
            if not ok:failures.append(row)
            print('CHECK '+json.dumps(row),flush=True)
        wrong=dict(r3);wrong['number']=mp.nstr(mp.mpf(r3['number'])+mp.mpf('1e-90'),110)
        negative=not compare(wrong,control)[0]
        periods=[]
        for record in records:
            k=exact_input(record['params']['k'])
            if k<16/(3*mp.sqrt(3)):continue
            # Source proposition 3 versus proposition 5 and Legendre K.
            direct=2/mp.pi*mp.quad(lambda theta:1/mp.sqrt(k*k-48*mp.sin(theta)**2+64*mp.sin(theta)**4),[0,mp.pi/4,mp.pi/2])
            a=k*k-24+k*mp.sqrt(k*k+16);b=-k*k+24+k*mp.sqrt(k*k+16)
            legendre=2*mp.sqrt(2)*mp.ellipk(-b/a)/(mp.pi*mp.sqrt(a))
            delta=abs(direct-legendre)
            assert delta<mp.mpf('1e-125')
            periods.append({'k':record['params']['k'],'absolute_error':mp.nstr(delta,12)})
        # Reject nonfinite values and check the cubic solver on known roots.
        assert not compare(r3,mp.inf)[0]
        assert max(abs(z**3+2*z-3) for z in cubic_roots(mp.mpc(2),mp.mpc(-3)))<mp.mpf('1e-130')
    result={'checked_entries':len(rows),'total_entries':len(records),'failures':failures,'known_answer_control':known,'negative_control_rejected':negative,'symbolic_checks':True,'elliptic_derivative_checks':periods,'working_dps':135,'rows':rows,'r3_dilog_control':mp.nstr(control,130),'limitations':'Heuristic quadrature; Jensen and mpmath shared, original cubic and all three roots independently implemented. k=0 original cubic also integrated directly.'}
    print('RESULT '+json.dumps(result),flush=True)
    if failures or not known or not negative:raise SystemExit(1)
    return result

if __name__=='__main__':run(str(Path(__file__).with_name('entries.json')))
