"""T755: primitive Frobenius polynomials of diagonal quartic surfaces.

Requires SageMath and numberdb: sage -pip install numberdb
Run sage -python generate.py for offline JSON, --verify for every stored row,
or --publish to add the selected entries to the authorized private draft.
Set credentials and agent/model/run provenance outside this reusable program.
Filling entries does not offer or publish the draft.

Exact construction: Griffon arXiv:1612.08721v2 Definition 2.2, Theorem 2.3,
Remark 2.4. Multiply 1-beta*T^r over all ordered nonzero quartic-character
orbits under multiplication by p. beta is the four-variable zero-sum Jacobi
sum times the inverse coefficient characters, over F_(p^r). Use one generator
for both. Binary Jacobi associativity evaluates the sum when a nontrivial
intermediate character exists; the all-quadratic tuple has zero-sum sum Q.
No Tate twist, root extraction of eigenvalues, numerical rounding, or omission
of primitive algebraic classes. The polynomial variable T is not a parameter.
Default bounds are explicitly exploratory coverage choices; see the attached
argument-selection.md. The one-minus model (1,1,-1) belongs to T729.
"""
import argparse
from functools import lru_cache
from itertools import product, permutations
import json
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()
B = tuple(b for b in product(range(1, 4), repeat=4) if sum(b) % 4 == 0)
assert len(B) == 21
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(2, 11):
        for k in (n, -n):
            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 character_context(p, r):
    q = ZZ(p)**r
    F = GF(q, 'u')
    g = F.multiplicative_generator()
    # No quartic character is needed over F_p for the fixed 2222 orbit
    # when p = 3 mod 4. Its character is quadratic of value (-1)^e.
    modulus = 4 if (q-1) % 4 == 0 else 2
    root = I if modulus == 4 else K(-1)
    log = {}
    x = F(1)
    for e in range(int(q-1)):
        log[x] = e % modulus
        x *= g
    assert x == 1 and len(log) == q-1
    def chi(b, x):
        x = F(x)
        if x == 0:
            return K(0)
        assert (b * (q-1)) % 4 == 0
        exponent = b if modulus == 4 else b//2
        return root**(exponent*log[x])
    return F, chi

@lru_cache(maxsize=None)
def jacobi(p, r, b):
    F, chi = character_context(p, r)
    q = ZZ(p)**r
    if b == (2, 2, 2, 2):
        return K(q)
    # Permutation symmetry of the zero-sum definition allows a pairing
    # whose intermediate character is nontrivial.
    u, v, w, z = next(c for c in permutations(b) if (c[0]+c[1]) % 4)
    j1 = sum((chi(u, x)*chi(v, 1-x) for x in F), K(0))
    j2 = sum((chi((u+v) % 4, x)*chi(w, 1-x) for x in F), K(0))
    result = chi((u+v+w) % 4, F(-1))*j1*j2
    assert result*result.conjugate() == q*q
    return result

@lru_cache(maxsize=None)
def orbits(p):
    remaining = set(B)
    answer = []
    for b in B:
        if b not in remaining:
            continue
        orbit = [b]
        c = tuple(p*x % 4 for x in b)
        while c != b:
            assert c not in orbit
            orbit.append(c)
            c = tuple(p*x % 4 for x in c)
        remaining.difference_update(orbit)
        answer.append(tuple(orbit))
    assert not remaining and sum(map(len, answer)) == 21
    return tuple(answer)

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

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

    def value(self, params, digits=100):
        a = parse_model(params['a'])
        p = ZZ(params['p'])
        if p < 3 or not p.is_prime():
            raise ValueError('p must be an odd prime')
        if (a[0]*a[1]*a[2]) % p == 0:
            raise ValueError('bad place for the displayed model')
        S = PolynomialRing(K, 'T')
        t = S.gen()
        value = S(1)
        for orbit in orbits(int(p)):
            b = orbit[0]
            r = len(orbit)
            F, chi = character_context(int(p), r)
            twist = K(1)
            for bj, cj in zip(b, (1,)+a):
                twist *= chi(bj, F(cj))
            beta = jacobi(int(p), r, b)/twist
            value *= 1-beta*t**r
        result = R([ZZ(c) for c in value.list()])
        assert result.degree() == 21 and result[0] == 1
        assert all(type(c).__name__ == 'Integer' for c in result.list())
        return result

def computed_records():
    generator = DiagonalPrimitive()
    for params in generator.enumerate():
        poly = generator.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(DiagonalPrimitive().publish())
    elif args.verify:
        print(DiagonalPrimitive().verify(sample=None))
    else:
        print(json.dumps(list(computed_records()), indent=2))
