"""T762: Frobenius polynomials of hypergeometric motives of K3 type.

Install full SageMath and numberdb, then run:
    sage -pip install numberdb
    sage -python generate.py                 # verify all stored entries
    sage -python generate.py --preview       # compute without writing
    sage -python generate.py --publish       # fill authorized target only

The standard rational motive has cyclotomic numerator A and denominator
[1,1,1], rank 3, weight 2, and no additional twist. Sage uses the classical
series coordinate z; Magma/PARI use its reciprocal. Sage's euler_factor
uses p-adic trace reconstruction and the even-weight functional equation.
All values are exact polynomials in ZZ[T]; no decimal digit claim is needed.

The default reference slice is every height<=9 rational z with z and 1-z
{2,3}-units, for all four rank-three MUM templates and every prime 5<=p<=13.
This finite slice and these cutoffs are noncanonical; they control possible
bad primes and cover split/nonsplit residue classes before greater depth.
The natural mathematical domain is larger. See argument-selection.md.
For another value use K3Frobenius().value({'template':'2.4','z':'2/3','p':17},100).
The target account and upload provenance are supplied by the session, never
hard-coded in this reusable mathematical source. Default writes are disabled.
"""
import argparse
from functools import lru_cache
import numberdb.sage as numberdb
from sage.rings.integer_ring import ZZ
from sage.rings.rational_field import QQ
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
from sage.symbolic.ring import SR  # initialize symbolic machinery before HGM
from sage.modular.hypergeometric_motive import HypergeometricData

TEMPLATES = (('2.2.2', (2, 2, 2)), ('2.3', (2, 3)),
             ('2.4', (2, 4)), ('2.6', (2, 6)))
POLYNOMIALS = PolynomialRing(ZZ, 'T')


def unit_23(n):
    n = abs(ZZ(n))
    if not n:
        return False
    for p in (2, 3):
        while n % p == 0:
            n //= p
    return n == 1


def reference_arguments(height=9):
    return sorted({QQ(u) / QQ(v) for v in range(1, height + 1)
                   for u in range(-height, height + 1)
                   if ZZ(u).gcd(v) == 1 and unit_23(u) and unit_23(v)
                   and unit_23(u-v)})


@lru_cache(None)
def motive(template):
    A = dict(TEMPLATES)[template]
    return HypergeometricData(cyclotomic=(list(A), [1, 1, 1]))


class K3Frobenius(numberdb.Generator):
    table = 'T762'
    parameters = ('template', 'z', 'p')
    type = 'Z[]'
    digits = 100  # exact types ignore the significant-digit target
    rigour = 'exact'

    def enumerate(self):
        for template, _ in TEMPLATES:
            for z in reference_arguments():
                for p in (5, 7, 11, 13):
                    yield {'template': template, 'z': str(z), 'p': p}

    def value(self, params, digits):
        template = str(params['template'])
        z = QQ(params['z'])
        p = ZZ(params['p'])
        if template not in dict(TEMPLATES) or not p.is_prime() or z in (0, 1):
            raise ValueError('Unknown template, nonprime, or singular specialization')
        A = dict(TEMPLATES)[template]
        if any(a % p == 0 for a in A) or any(
                ZZ(n) % p == 0 for n in
                (z.numerator(), z.denominator(), z.numerator()-z.denominator())):
            raise ValueError('The table only defines smooth good-prime factors')
        return POLYNOMIALS(motive(template).euler_factor(z, p))


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--publish', action='store_true')
    parser.add_argument('--preview', action='store_true')
    args = parser.parse_args()
    generator = K3Frobenius()
    if args.publish:
        print(generator.publish())
    elif args.preview:
        print(generator.preview())
    else:
        print(generator.verify(sample=None))
