"""T754: transcendental Frobenius polynomials of diagonal quartic surfaces.

Requires SageMath and numberdb. Install: sage -pip install numberdb
Run: sage -python generate.py (offline JSON);
use sage -python generate.py --verify to compare every stored row, or
sage -python generate.py --publish to add entries to the authorized draft.
The latter fills the draft; it does not offer or publish it. Configure credentials
and upload provenance outside this file, as documented by numberdb.

Exact arithmetic only: J4=chi(-1)^3*J(chi,chi)*J(chi^2,chi), obtained by
normalizing the fourth zero-sum variable and applying Jacobi associativity.
All intermediate characters in the binary-sum reduction are nontrivial.
Griffon arXiv:1612.08721v2 Definition 2.2, Theorem 2.3, Remark 2.4 gives
prod_A(1-J4*chi(a1*a2*a3)^(-1)*T^|A|). Restrict characters to
(1,1,1,1),(3,3,3,3), identified geometrically in Gvirtz–Skorobogatov
arXiv:1905.11869v2 Section 3.1, with twists in Remarks 2.10 and 3.10.
There is no Tate twist. Coefficient characters and Jacobi sums use the same
finite-field generator. Default bounds are coverage choices, not the domain.
"""
import argparse
from functools import lru_cache
import json
import os
import sys
import numberdb.sage as numberdb
from sage.rings.integer_ring import ZZ
from sage.rings.finite_rings.finite_field_constructor import GF
from sage.rings.number_field.number_field import CyclotomicField
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing

K = CyclotomicField(4)
I = K.gen()
R = PolynomialRing(ZZ, 'T')
T = R.gen()
COMPARISONS = ((1, 2, 8), (1, -2, -8), (2, -2, -4),
               (-2, 4, 8), (1, 2, -2), (1, 8, -8))

def models():
    yield (1, 1, 1)
    for n in range(1, 11):
        for k in (n, -n):
            if k != 1:
                yield (1, 1, k)
    yield from COMPARISONS

def model_key(a):
    return '.'.join(str(x) for x in a)

def parse_model(key):
    a = tuple(ZZ(x) for x in str(key).split('.'))
    if len(a) != 3 or any(x == 0 for x in a):
        raise ValueError('a must encode three nonzero integer coefficients')
    if any(e >= 4 for x in a for _, e in abs(x).factor()):
        raise ValueError('coefficients must be fourth-power-free')
    return a

@lru_cache(maxsize=None)
def jacobi_context(p):
    """One exact sum per prime, shared by coefficient twists; no stored values."""
    p = ZZ(p)
    if p < 3 or not p.is_prime():
        raise ValueError('p must be an odd prime')
    r = 1 if p % 4 == 1 else 2
    q = p**r
    field = GF(q, 'u')
    g = field.multiplicative_generator()
    powers = (K(1), I, K(-1), -I)
    chi = {field(0): K(0)}
    z = field(1)
    for e in range(int(q - 1)):
        chi[z] = powers[e % 4]
        z *= g
    assert z == 1 and len(chi) == q
    j11 = sum((chi[x] * chi[1 - x] for x in field), K(0))
    j21 = sum((chi[x]**2 * chi[1 - x] for x in field), K(0))
    j4 = chi[field(-1)]**3 * j11 * j21
    assert j4 * j4.conjugate() == q**2
    return r, field, chi, j4

class DiagonalTranscendental(numberdb.Generator):
    table = 'T754'
    parameters = ('a', 'p')
    type = 'Z[]'
    rigour = 'exact'
    digits = 100

    def enumerate(self):
        for a in models():
            product = ZZ(a[0]) * a[1] * a[2]
            for p in range(3, 98, 2):
                if ZZ(p).is_prime() and product % p:
                    yield {'a': model_key(a), 'p': p}

    def value(self, params, digits=100):
        a = parse_model(params['a'])
        p = ZZ(params['p'])
        product = a[0] * a[1] * a[2]
        if product % p == 0:
            raise ValueError('bad place for the displayed model')
        r, field, chi, j4 = jacobi_context(p)
        beta = j4 / chi[field(product)]
        if r == 1:
            result = R([1, ZZ(-beta - beta.conjugate()), ZZ(beta * beta.conjugate())])
        else:
            result = R([1, 0, -ZZ(beta)])
        assert result.degree() == 2 and result[0] == 1
        assert all(type(x).__name__ == 'Integer' for x in result.list())
        return result

def computed_records():
    gen = DiagonalTranscendental()
    for params in gen.enumerate():
        poly = gen.value(params)
        yield {'params': params, 'number': str(poly),
               'coefficients': [int(c) for c in poly.list()]}

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--publish', action='store_true')
    parser.add_argument('--verify', action='store_true')
    args = parser.parse_args()
    if args.publish:
        print(DiagonalTranscendental().publish())
    elif args.verify:
        print(DiagonalTranscendental().verify(sample=None))
    else:
        print(json.dumps(list(computed_records()), indent=2))
