"""T836: twisted Laplacian determinants of CM flat tori.

Install numberdb and SageMath (or the modular passagemath rings/symbolics).
  sage -pip install numberdb
  sage -python generate.py             # offline 100-digit entries, no writes
  sage -python generate.py --verify    # reproduce every stored entry
  sage -python generate.py --publish   # explicitly fill the existing draft
Use your own configured API key for the last two commands. Engine/model/run
provenance belongs in the environment, never in this reusable generator.

Parameters: primitive a*u^2+b*u*v+c*v^2 with 0<=b<=a<=c; the marked
area-one periods are (1,tau)/sqrt(Im(tau)), tau=(-b+i*sqrt(4ac-b^2))/(2a).
eps1,eps2 give signs on these ordered periods and exclude (0,0).
convention is det or logdet. The default discriminant bound is 100.

Production uses log|eta| products in Arb balls, with exact input coefficients.
For r=|exp(2*pi*i*tau)|<1 the omitted log product after N terms is at most
r^(N+1)/((1-r)*(1-r^(N+1))). Add this outward bound before eta ratios,
exponentiation and subtraction. Working precision is ceil(digits*log2(10))+160
bits. The finite selection and exact exceptions are explained in the attached
argument-selection.md and check-notes.md. No rounded value is snapped to zero.
"""
import numberdb.sage as numberdb
from sage.rings.integer_ring import ZZ
from sage.rings.rational_field import QQ
from sage.rings.real_arb import RealBallField
from sage.rings.complex_arb import ComplexBallField
from functools import lru_cache
from math import gcd, isqrt
import json, sys

SECTORS=((0,1),(1,0),(1,1))

def reduce_unoriented(a,b,c):
    g=gcd(gcd(a,b),c); a,b,c=a//g,b//g,c//g
    while True:
        q=(a-b)//(2*a)
        a,b,c=a,b+2*a*q,a*q*q+b*q+c
        if a>c: a,b,c=c,-b,a
        else: return a,abs(b),c

def cover_form(a,b,c,sector):
    # Primitive quadratic form of the inherited double-cover period lattice.
    if sector==(0,1): return reduce_unoriented(a,2*b,4*c)
    if sector==(1,0): return reduce_unoriented(4*a,2*b,c)
    if sector==(1,1): return reduce_unoriented(4*a,2*b-4*a,a-b+c)
    raise ValueError('nontrivial sign sector required')

def forms(bound=100):
    answer=[]
    for a in range(1,isqrt(bound//3)+1):
        for b in range(a+1):
            for c in range(a,(bound+b*b)//(4*a)+1):
                d=4*a*c-b*b
                if 3<=d<=bound and gcd(gcd(a,b),c)==1:
                    answer.append((a,b,c))
    return sorted(answer,key=lambda t:(4*t[0]*t[2]-t[1]**2,*t))

def logabs_eta(tau):
    R=tau.real().parent(); C=tau.parent()
    Q=(2*R.pi()*C(0,1)*tau).exp(); r=Q.abs()
    assert r<1 and r>0
    result=-R.pi()*tau.imag()/12
    target=R(2)**(-R.precision()+24)
    qpower=Q; rpower=r; n=0
    while True:
        tail=rpower/((1-r)*(1-rpower))
        if tail<target: break
        result+=(1-qpower).abs().log()
        qpower*=Q; rpower*=r; n+=1
    return result.add_error(tail), n, tail

@lru_cache(maxsize=None)
def raw_logs(a,b,c,digits=100):
    assert 1<=a<=c and 0<=b<=a and gcd(gcd(a,b),c)==1
    R=RealBallField(numberdb.bits(digits,losing=160)); C=ComplexBallField(R.precision())
    y=R(4*a*c-b*b).sqrt()/(2*a); tau=C(-R(b)/(2*a),y)
    vals=[logabs_eta(t) for t in (tau,2*tau,tau/2,(tau+1)/2)]
    base=vals[0][0]
    logs=(R(4).log()+4*(vals[1][0]-base),4*(vals[2][0]-base),4*(vals[3][0]-base))
    assert all(t.is_finite() for t in logs)
    return logs, vals

class TwistedDeterminants(numberdb.Generator):
    table='T836'
    parameters=('a','b','c','eps1','eps2','convention')
    type='R'; digits=100; rigour='proven'

    def enumerate(self,bound=100):
        for a,b,c in forms(bound):
            for e1,e2 in SECTORS:
                for convention in ('det','logdet'):
                    yield dict(zip(self.parameters,(a,b,c,e1,e2,convention)))

    def value(self,params,digits):
        a,b,c,e1,e2=(int(params[k]) for k in self.parameters[:5])
        conv=params['convention']; assert conv in ('det','logdet')
        idx=SECTORS.index((e1,e2))
        # Proven exact values, not a decimal-pattern test; see check-notes.md.
        exact=None
        if cover_form(a,b,c,(e1,e2))==(a,b,c): exact=ZZ(2)
        if (a,b,c)==(1,1,2): exact=ZZ((1,2,2)[idx])
        if (a,b,c,e1,e2)==(1,0,7,1,1): exact=ZZ(4)
        if exact is not None:
            if conv=='det': return exact
            if exact==1: return ZZ(0)
            return RealBallField(numberdb.bits(digits,losing=160))(exact).log()
        logs,_=raw_logs(a,b,c,digits)
        return logs[idx] if conv=='logdet' else logs[idx].exp()

if __name__=='__main__':
    g=TwistedDeterminants()
    if '--publish' in sys.argv:
        print(g.publish(message='Fill checked sign-holonomy determinants; proposal https://github.com/numberdb/numberdb-data/issues/395'))
    elif '--verify' in sys.argv: print(g.verify(sample=None))
    else:
        from numberdb._write import to_text
        for p in g.enumerate(): print(json.dumps({'params':p,'number':to_text(g.value(p,100),100)}),flush=True)
