"""T737: Fourier coefficients of the Kubota cubic theta function.

Usage (SageMath or passagemath plus numberdb):
    sage -python generate.py                 # preview, no network writes
    sage -python generate.py --publish       # authorized additive upload
    sage -python generate.py --verify        # reproduce every stored entry

Dunn--Radziwill, arXiv:2109.07463v3, (1.5), (5.6)--(5.8).
Parameters a,b give m=a+b*omega=lambda^3*mu. The default enumerates every
nonzero support point with N(m)<=1000, modulo the even sign symmetry.
No coprimality restriction is imposed between the squarefree c and cube d.

Exact quotient representatives and residue fields give an integer polynomial
in zeta_(3*N(c)); reduction modulo its cyclotomic polynomial preserves an
exact witness. A ninth-root factor and a positive square root finish tau.
Arb at max(512,bits(digits)+128) encloses the polynomial and all radicals.
Exact zero and rational components are decided algebraically (component
squares reduce to rational squares), never by a decimal pattern. Every
approximate component is required finite and to have >digits+15 relative
bits converted to decimal digits. There is no analytic truncation here.

The build's exact witnesses, independent checks and truncation evidence are
separate attachments. Credentials and agent provenance are session settings.
"""
import argparse
import functools
import json
import math
from fractions import Fraction
from pathlib import Path
import numberdb.sage as numberdb
from numberdb._write import to_text
from numberdb._wire import ComplexInterval
from sage.rings.integer_ring import ZZ
from sage.rings.rational_field import QQ
from sage.rings.number_field.number_field import CyclotomicField
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
from sage.rings.complex_arb import ComplexBallField

K = CyclotomicField(3)
omega = K.gen()
lam = 1 + 2*omega
P = PolynomialRing(QQ, 'X')
X = P.gen()
BOUND = 1000


def coords(z):
    q = list(K(z));q += [QQ(0)]*(2-len(q))
    assert all(t.denominator()==1 for t in q)
    return tuple(int(t) for t in q)


def norm(z):
    return int(K(z).norm())


def primary(z):
    for u in (K(1),-K(1),omega,-omega,omega**2,-omega**2):
        a,b=coords(u*z)
        if a%3==1 and b%3==0:return u*z
    raise ValueError('ramified argument has no primary associate')


def representative(z):
    a,b=coords(z)
    return z if (2*a-b>0 or (2*a-b==0 and b>0)) else -z


@functools.lru_cache(None)
def primary_elements(bound):
    r=math.isqrt(2*bound)+2
    out=[]
    for a in range(-r,r+1):
        if a%3!=1:continue
        for b in range(-r,r+1):
            n=a*a-a*b+b*b
            if b%3==0 and 0<n<=bound:out.append((n,a,b))
    return tuple(sorted(out))


@functools.lru_cache(None)
def squarefree(bound):
    return tuple((n,a,b) for n,a,b in primary_elements(bound)
                 if all(int(e)==1 for p,e in K.ideal(a+b*omega).factor()))


@functools.lru_cache(None)
def selection(bound=BOUND):
    """Product enumeration, not a Cartesian selection of c,d,n,j."""
    dmax=int(ZZ(bound).nth_root(3,truncate_mode=True)[0])
    out={}
    for nd,da,db in primary_elements(dmax):
        d=da+db*omega
        for nc,ca,cb in squarefree(bound//(nd**3)):
            c=ca+cb*omega;z=c*d**3
            for branch,start,power in [('B',0,0),('A',1,2)]:
                n=start;k=power
                while nc*nd**3*3**k<=bound:
                    for j in ([0] if branch=='B' else [0,1,2]):
                        m=representative(omega**j*lam**k*z);a,b=coords(m)
                        assert (a,b) not in out
                        out[a,b]={'m':[a,b],'norm_m':norm(m),'branch':branch,
                                  'n':n,'j':j,'c':[ca,cb],'norm_c':nc,
                                  'd':[da,db],'norm_d':nd}
                    n+=1;k+=3
    return tuple(sorted(out.values(),key=lambda r:(r['norm_m'],*r['m'])))


@functools.lru_cache(None)
def gauss_polynomial(ca,cb,ua,ub):
    c=K(ca+cb*omega);u=K(ua+ub*omega);nc=norm(c)
    if nc==1:return 3,P(1)
    fields=[]
    for ideal,e in K.ideal(c).factor():
        assert e==1
        f=ideal.residue_field('t'); roots={f(omega**j):j for j in range(3)}
        fields.append((f,(int(ideal.norm())-1)//3,roots))
    L=3*nc;counts=[0]*L;seen=0
    for x in K.ideal(c).residues():
        seen+=1;exponent=0
        for f,power,roots in fields:
            y=f(x)
            if y==0:break
            exponent+=roots[y**power]
        else:
            trace=QQ((u*x/c).trace());t=trace*nc
            assert t.denominator()==1
            counts[(nc*exponent+3*int(t))%L]+=1
    assert seen==nc
    phi=P.cyclotomic_polynomial(L)
    return L,P(counts)%phi


def conjugate_polynomial(v,L,phi):
    return P({(-int(k))%L:q for k,q in v.dict().items()})%phi


@functools.lru_cache(None)
def witness(ca,cb,branch,n,j,nd):
    u=omega**j*lam**2 if branch=='A' else K(1)
    ua,ub=coords(u);old,g=gauss_polynomial(ca,cb,ua,ub)
    L=math.lcm(old,9 if branch=='A' else 1);phi=P.cyclotomic_polynomial(L)
    v=P({(-int(k)*(L//old))%L:q for k,q in g.dict().items()})%phi
    if branch=='A':
        phase=[0,-1,1][j]*(L//9)
        v=P({(int(k)+phase)%L:q for k,q in v.dict().items()})%phi
    r=QQ(nd)*3**(n+(4 if branch=='A' else 5))/norm(ca+cb*omega)
    vc=conjugate_polynomial(v,L,phi)
    real=(v+vc)/2; imag_times_i=(v-vc)/2
    re2=(real**2*r)%phi;im2=(-imag_times_i**2*r)%phi
    return L,v,r,re2,im2


def component_exact(square,ball):
    if square==0:return QQ(0)
    if square.degree()<=0 and square[0]>=0 and square[0].is_square():
        q=square[0].sqrt()
        assert ball>0 or ball<0
        if ball<0:q=-q
        return q
    return ball


def coefficient(row,digits=100):
    L,v,r,re2,im2=witness(*row['c'],row['branch'],row['n'],row['j'],row['norm_d'])
    B=ComplexBallField(max(512,numberdb.bits(digits,losing=128)))
    z=(B(0,2)*B.pi()/L).exp();answer=v(z)*B(r).sqrt()
    re=component_exact(re2,answer.real());im=component_exact(im2,answer.imag())
    for part in (re,im):
        if isinstance(part,type(QQ(1))):continue
        assert part.is_finite() and not part.contains_zero()
        assert part.rad() < abs(part.mid()) * QQ(1)/10**(digits+15)
    if im==0:return re
    return B(re,im)


class CubicTheta(numberdb.Generator):
    table='T737'
    parameters=('a','b')
    type='C'
    digits=100
    rigour='proven'
    files=('generate.py',)
    def enumerate(self):
        for r in selection():yield dict(zip(self.parameters,r['m']))
    def value(self,params,digits):
        key=(int(params['a']),int(params['b']))
        rows={tuple(r['m']):r for r in selection()}
        return coefficient(rows[key],digits)


if __name__=='__main__':
    p=argparse.ArgumentParser();p.add_argument('--publish',action='store_true');p.add_argument('--verify',action='store_true');p.add_argument('--checkpoint',action='store_true');args=p.parse_args()
    g=CubicTheta()
    if args.publish:g.publish(removing=False)
    elif args.verify:print(g.verify(sample=None))
    elif args.checkpoint:
        rows=[];witnesses=[]
        for r in selection():
            val=coefficient(r);rows.append({'params':dict(zip(g.parameters,r['m'])),'number':to_text(val,100)})
            L,v,rad,re2,im2=witness(*r['c'],r['branch'],r['n'],r['j'],r['norm_d'])
            witnesses.append({'m':r['m'],'L':L,'coefficients':{str(k):str(q) for k,q in v.dict().items()},'radicand':str(rad),'real_squared_polynomial':str(re2),'imag_squared_polynomial':str(im2)})
        print(json.dumps({'entries':rows,'selection':selection(),'witnesses':witnesses}))
    else:
        rows=list(g.enumerate())
        values=[to_text(g.value(p,100),100) for p in rows]
        print(json.dumps({'table':g.table,'entries':len(rows),'largest_number_characters':max(map(len,values)),'number_characters':sum(map(len,values))}))
