"""T821: Kashaev invariants of twist knots.

Install SageMath 10.9 (or compatible), then `sage -pip install numberdb`.
    sage -python generate.py              # offline, checks and JSON checkpoint
    sage -python generate.py --verify     # reproduce every stored value
    sage -python generate.py --publish    # explicitly fill target, never offer
For private access set NUMBERDB_API_KEY, or NUMBERDB_KEY_FROM_STDIN=1.
The invoking session supplies engine/model/run attribution, never this file.

Masbaum (2003), Figure 3 and section 5, fixes the signed full-twist index p,
zero framing, reduction by the unknot, N=representation dimension, q=A^4.
Nawata--Ramadevi--Zodinmawia arXiv:1209.1409v2 section 2.1 gives the
positive/negative division-free multisums used here (not superpolynomials).
The root is exp(+2*pi*i/N); mirror means q -> q^-1, not p -> -p.
The family is p!=0, N>=2; source only at amphichiral p=-1. Default p covers
1<=|p|<=4, every distinct hand and N=2..32. These are discrete reference
cutoffs, not a continuous grid. N=1 and p=0 are off-table controls.

All multisum operations are exact in Q(zeta_N), with Gaussian binomials
computed by addition/multiplication recurrence. Arb evaluates the canonical
power-basis polynomial at an enclosing positive-angle exponential at 768 bits
(or numberdb.bits(digits,losing=384), whichever is larger). No approximation
is used to decide exact rational components. The real part is (v+bar(v))/2;
when 4 divides N the imaginary part is (v-bar(v))/(2*zeta_N^(N/4)).
For the other N, a rational imaginary component is necessarily zero, since
i is not in Q(zeta_N). Exact components are returned as QQ rationals. Every
other component carries its Arb error bound; the serializer retains 100
significant digits. Independent checks, including stored decimal containment,
are in check_values.py. Neither verify() nor this generator is that check.
"""
import argparse
from functools import lru_cache
import json
import os
import sys
from fractions import Fraction
import numberdb.sage as numberdb
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.complex_arb import ComplexBallField
from sage.rings.real_arb import RealBallField
from sage.rings.real_mpfi import RealIntervalField
from numberdb._write import to_text

@lru_cache(maxsize=None)
def root_data(N):
    K = CyclotomicField(N)
    z = K.gen()
    # Polynomial recurrence, including at roots, has no singular quotients.
    g = [[K.one()]]
    for n in range(1, N):
        row = [K.one()]
        for k in range(1, n):
            row.append(g[n-1][k-1] + z**k * g[n-1][k])
        row.append(K.one())
        g.append(row)
    return K, z, g

@lru_cache(maxsize=None)
def exact_source(p, N):
    if N < 1:
        raise ValueError('N must be positive')
    if p == 0 or N == 1:
        return QQ.one()
    K, z, gaussian = root_data(N)
    chain = [K.one() for k in range(N)]
    for depth in range(2, abs(p)+1):
        chain = [sum((z**(s*(s+1) if p>0 else -s*(k+1))
                      * gaussian[k][s] * chain[s] for s in range(k+1)), K.zero())
                 for k in range(N)]
    product, total = K.one(), K.zero()
    for k in range(N):
        outer = z**k if p>0 else ZZ(-1)**k*z**(-(k*(k+1)//2))
        total += outer * product * chain[k]
        product *= (1-z**(1-N+k)) * (1-z**(1+N+k))
    return total

def exact_value(p, hand, N):
    if hand not in ('source','mirror'):
        raise ValueError('unknown hand')
    v=exact_source(p,N)
    return v if hand=='source' else v.conjugate()

def rational_or_none(v):
    try:
        return QQ(v)
    except (TypeError,ValueError):
        return None

def components(v, N):
    c = v.conjugate()
    real = rational_or_none((v+c)/2)
    if v==c:
        imaginary=QQ.zero()
    elif N%4==0:
        imaginary=rational_or_none((v-c)/(2*root_data(N)[1]**(N//4)))
    else:
        imaginary=None
    return real,imaginary

def enclosed_value(p, hand, N, digits=100):
    v=exact_value(p,hand,N)
    bits=max(768,numberdb.bits(digits,losing=384))
    R=RealBallField(bits);C=ComplexBallField(bits)
    theta=2*R.pi()/N
    z=C(0,theta).exp()
    if N>2:
        assert z.imag()>0
    coeffs=v.list()
    b=C.zero()
    for c in reversed(coeffs): b=b*z+C(c)
    re,im=components(v,N)
    # Arb bounds include the root and all polynomial evaluation error.
    def faithful_part(exact, ball):
        if exact is not None:
            return Fraction(int(exact.numerator()),int(exact.denominator()))
        interval=RealIntervalField(bits)(ball)
        endpoints=[x.exact_rational() for x in (interval.lower(),interval.upper())]
        assert endpoints[0]<endpoints[1]
        return numberdb.RealInterval(*[Fraction(int(x.numerator()),int(x.denominator())) for x in endpoints])
    real_part,imaginary_part=faithful_part(re,b.real()),faithful_part(im,b.imag())
    if im==0:
        return re if re is not None else real_part
    return numberdb.ComplexInterval(real_part,imaginary_part)

class Kashaev(numberdb.Generator):
    table='T821'
    parameters=('p','hand','N')
    type='C'
    digits=100
    rigour='proven'
    files=('generate.py',)
    def enumerate(self,p_limit=4,color_max=32):
        for d in range(1,int(p_limit)+1):
            for p in (d,-d):
                for hand in (('source',) if p==-1 else ('source','mirror')):
                    for N in range(2,int(color_max)+1):
                        yield {'p':p,'hand':hand,'N':N}
    def value(self,params,digits):
        p,hand,N=int(params['p']),str(params['hand']),int(params['N'])
        if p==0 or N<2: raise ValueError('stored domain requires p!=0, N>=2')
        return enclosed_value(p,hand,N,digits)

def checkpoint():
    assert exact_source(-1,2)==5 and exact_source(-1,3)==13 and exact_source(-1,4)==27
    assert exact_source(1,3)==1+6*root_data(3)[1]**2
    assert all(exact_source(0,N)==1 for N in range(1,33))
    assert all(exact_source(p,1)==1 for p in range(-4,5))
    rows=[]
    for params in Kashaev().enumerate():
        v=exact_value(**params);re,im=components(v,params['N'])
        rows.append({'params':params,'number':to_text(enclosed_value(**params),100),
                     'cyclotomic_coefficients':[str(QQ(c)) for c in v.list()],
                     'exact_real':str(re) if re is not None else None,
                     'exact_imag':str(im) if im is not None else None})
    return {'table':'T821','working_bits':768,'digits':100,'rows':rows}

if __name__=='__main__':
    a=argparse.ArgumentParser(description=__doc__);a.add_argument('--publish',action='store_true');a.add_argument('--verify',action='store_true');args=a.parse_args()
    if os.environ.get('NUMBERDB_KEY_FROM_STDIN')=='1':
        key=sys.stdin.read().strip()
        if '=' in key and key.split('=',1)[0].isupper():key=key.split('=',1)[1].strip().strip('\"\'')
        numberdb.configure(api_key=key)
    g=Kashaev()
    if args.publish or os.environ.get('NUMBERDB_PUBLISH')=='1':print(g.publish(message=os.environ.get('NUMBERDB_EDIT_MESSAGE','')))
    elif args.verify:print(g.verify(sample=None))
    else:print(json.dumps(checkpoint(),indent=2))
