"""T774: CM coefficients of the mirror quartic K3 family.

Requires SageMath (or passagemath with real Arb) and numberdb.
    sage -python generate.py                 # verify, never write by default
    sage -python generate.py --publish       # fill the authorized existing draft

r is a positive integer, tau=i*sqrt(r); q=exp(-2*pi*sqrt(r)). The positive
coefficient is ((R+128+4096/R)/256)^(1/4), R=q^-1 prod(1+q^n)^-24.
The omitted positive log-product tail is <=q^(N+1)/(1-q). Arb encloses all
operations and both positive square roots. At least 600 working bits support
100 recorded significant digits; check_evidence.py measures the actual bounds.
The default enumeration is the arithmetic reference slice 1 <= r <= 10,
retaining nonmaximal orders and square factors, with no completeness claim.
Credentials and agent/model provenance belong in the calling environment.
"""
import os
import sys
from functools import lru_cache
import numberdb.sage as numberdb
from sage.rings.integer_ring import ZZ
from sage.rings.real_arb import RealBallField


@lru_cache(maxsize=256)
def eta_quotient(r, working_bits):
    r = ZZ(r)
    if r <= 0:
        raise ValueError('r must be a positive integer')
    B = RealBallField(working_bits)
    q = (-2 * B.pi() * B(r).sqrt()).exp()
    target = B(2) ** (-working_bits - 24)
    total = B(0)
    power = q
    n = 0
    while True:
        n += 1
        total += (1 + power).log()
        power *= q
        tail = power / (1-q)
        if tail < target:
            break
    # Symmetric expansion includes the positive omitted sum [0,tail].
    total = total.add_error(tail)
    R = (-24 * total).exp() / q
    if not R.is_finite() or not R > 0:
        raise ArithmeticError('Invalid eta quotient enclosure')
    return R, n, tail


def coefficient(r, digits=100):
    working = max(600, numberdb.bits(digits, losing=160))
    R, _, _ = eta_quotient(ZZ(r), working)
    value = ((R + 128 + 4096/R)/256).sqrt().sqrt()
    if not value.is_finite() or not value > 1:
        raise ArithmeticError('Invalid positive quartic coefficient')
    return value


class MirrorQuarticCM(numberdb.Generator):
    table = 'T774'
    parameters = ('r',)
    type = 'R'
    digits = 100
    rigour = 'proven'

    def enumerate(self, limit=10):
        for r in range(1, int(limit)+1):
            yield {'r': r}

    def value(self, params, digits):
        return coefficient(params['r'], digits)


if __name__ == '__main__':
    if os.environ.get('NUMBERDB_KEY_FROM_STDIN') == '1':
        numberdb.configure(api_key=sys.stdin.read().strip())
    g = MirrorQuarticCM()
    if '--publish' in sys.argv or os.environ.get('NUMBERDB_PUBLISH') == '1':
        print(g.publish())
    else:
        print(g.verify(sample=None))
