import numberdb.sage as numberdb
from sage.rings.integer_ring import ZZ
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing
from sage.modular.dirichlet import DirichletGroup
from itertools import product

def split_fermat(n,d,p):
    """Primitive det(1-T*Frob) for the one-minus model at a split prime."""
    n,d,p=map(ZZ,(n,d,p))
    if n<2 or n%2 or d<3 or not p.is_prime() or (p-1)%d:
        raise ValueError('Require even n>=2, d>=3, and prime p=1 mod d')
    D=DirichletGroup(p);chi=D.gen()**((p-1)//d)
    S=PolynomialRing(D.base_ring(),'T');T=S.gen();P=S.one()
    for tail in product(range(1,int(d)),repeat=int(n)+1):
        if sum(tail)%d==0:continue
        J=D.base_ring().one();s=tail[0]
        for t in tail[1:]:
            J *= -p if s==0 else (chi**s).jacobi_sum(chi**t)
            s=(s+t)%d
        P*=1-J*T
    return PolynomialRing(ZZ,'T')(P)

# The displayed routine covers split primes; the attachment also handles
# nonsplit primes by exact p-orbit descent. Its default stored selection is:
def default_selection():
    primes=(2,3,5,7,11,13,17,19,23,29,31)
    return [(n,d,p) for n,d in [(2,d) for d in range(3,7)]+[(4,3)]
            for p in primes if d%p and (n==2 or p>3)]

split_fermat(2,4,37)
