"""Reproduce T731: Period map of the Dwork quartic K3 family.

Install numberdb in Sage, then run:
  sage -pip install numberdb
  sage -python generate.py              # preview only
  sage -python generate.py --verify     # authenticated full stored comparison
  sage -python generate.py --publish    # explicit additive upload to own draft

The only input is the exact nonnegative rational quartic coefficient t != 1.
The default enumeration is the smooth Fermat fibre and all positive reduced
fractions a/b != 1 of height max(a,b)<=6, ordered by height then value.

Hartmann arXiv:1101.4601v1, Example 4.27 and Theorem 4.29 fix the logarithmic
period germ and its lift. Yang arXiv:2004.00820v1 (5.3), (5.15)-(5.17) identifies
it with i*K(1-lambda)/K(lambda), where K uses the elliptic PARAMETER.
Writing u=lambda/(2-lambda) gives z=4u^2(1-u^2). The selected branch is
  s=sqrt(1-z), u=sqrt((1-s)/2), lambda=2u/(1+u).
For real z>1 the UPPER-bank value has s=-i*sqrt(z-1). The remaining square
root has positive real part. For z<1 both square roots are positive real.
These roots continue the lambda~sqrt(z)>0 germ without winding. For z>1,
lambda has positive imaginary part, so neither elliptic argument crosses
its principal K branch cut. No modular reduction is applied.

Arb propagates exact rational inputs and all root and elliptic evaluation
uncertainties, including division by an explicitly nonzero denominator.
Working precision is numberdb.bits(digits, losing=180). Every nonzero output
component must retain at least digits+20 decimal digits as measured from the
ball radius, before numberdb rounds to the requested digits. The exact origin
is fixed by the smooth boundary value, not extrapolated numerically.
The independent PF and eta checks are in pf_check.py and check_evidence.py.
Session provenance and credentials belong to the caller, not this file.
"""
import os
import sys
import math
import numberdb.sage as numberdb
from numberdb._write import to_text
from sage.rings.rational_field import QQ
from sage.rings.complex_arb import ComplexBallField


def selection():
    yield QQ(0)
    for height in range(2,7):
        for t in sorted({QQ(a)/QQ(b) for a in range(1,height+1)
                         for b in range(1,height+1)
                         if max(a,b)==height and math.gcd(a,b)==1 and a!=b}):
            yield t


def compute(t, digits=100, extra_bits=180, details=False):
    t=QQ(t)
    if t<0 or t==1:
        raise ValueError('t must be nonnegative rational, different from 1')
    C=ComplexBallField(numberdb.bits(digits,losing=extra_bits))
    i=C(0,1)
    if t==0:
        ans=C(QQ(1)/2,QQ(1)/2)
        return (ans,{'exact':True,'bits':int(C.precision())}) if details else ans
    z=C(t**(-4))
    s=(1-z).sqrt() if t>1 else -i*(z-1).sqrt()
    u=((1-s)/2).sqrt()
    lam=2*u/(1+u)
    denominator=lam.elliptic_k()
    if not all(x.is_finite() for x in (denominator.real(),denominator.imag())) or denominator.contains_zero():
        raise ArithmeticError('elliptic denominator is not separated from zero')
    ans=i*(1-lam).elliptic_k()/denominator
    if t>1:
        # Reality of both elliptic factors follows from 0<lambda<1.
        if not ans.real().is_zero():
            raise ArithmeticError('positive real branch lost exact zero')
    if not all(x.is_finite() for x in (ans.real(),ans.imag())):
        raise ArithmeticError('nonfinite period')
    for p in [ans.real(),ans.imag()]:
        if not p.is_zero() and not p.parent()(p.rad())<abs(p)*QQ(10)**(-digits-20):
            raise ArithmeticError('insufficient propagated component precision')
    if t==QQ(3)/4:
        # Exact Landen/TS certificate in mathematical-checks.md and cm_check.py:
        # 2*tau^2-tau+1=0 on this lift, so Re(tau)=1/4 exactly.
        if not ans.real().contains_exact(QQ(1)/4):
            raise ArithmeticError('CM certificate contradicts elliptic enclosure')
        ans=C(QQ(1)/4,ans.imag())
    meta={'exact':False,'bits':int(C.precision()),'lambda':str(lam),
          'denominator_abs_lower':str(abs(denominator).lower()),
          'real_radius':str(ans.real().rad()),'imag_radius':str(ans.imag().rad()),
          'real_accuracy_bits':str(ans.real().accuracy()),
          'imag_accuracy_bits':str(ans.imag().accuracy())}
    return (ans,meta) if details else ans


class DworkPeriod(numberdb.Generator):
    table='T731'
    parameters=('t',)
    type='C'
    digits=100
    rigour='proven'

    def enumerate(self):
        for t in selection():
            yield {'t':t}

    def value(self,params,digits):
        return compute(params['t'],digits)


if __name__=='__main__':
    if os.environ.get('NUMBERDB_KEY_FROM_STDIN')=='1':
        numberdb.configure(api_key=sys.stdin.read().strip())
    gen=DworkPeriod()
    if '--publish' in sys.argv:
        gen.publish(removing=False)
    elif '--verify' in sys.argv:
        gen.verify(sample=None)
    else:
        gen.preview()
