"""T839: p-adic roots of the plastic-constant polynomial.

Requires SageMath and numberdb (sage -pip install numberdb).
Run sage -python generate.py to verify all stored entries, or
sage -python generate.py --preview to compute without writing.
An authorized contributor may use --publish to add these entries to the draft;
this does not offer or publish the table. Set normal NumberDB provenance in
that session, never in this reusable file.

The default selection is every branch at primes <=29 and at 59. The latter is
the least completely split prime. k=1 and a is the least nonnegative simple
root residue. Integer Newton lifting doubles the certified modulus until
p^N >= 10^digits; Qp retains exactly that absolute precision. Hensel's lemma
(Conrad, Theorem 2.1) proves existence and uniqueness in each ball. No floating
point arithmetic or numerical root ordering selects a branch.
"""
import argparse
import numberdb.sage as numberdb
from sage.rings.integer_ring import ZZ
from sage.rings.padics.factory import Qp

PRIMES = (2,3,5,7,11,13,17,19,23,29,59)

def target_exponent(p, digits=100):
    n, modulus = 0, 1
    while modulus < 10**digits:
        modulus *= p
        n += 1
    return n

def simple_residues(p):
    return [a for a in range(p) if (a**3-a-1)%p == 0 and (3*a*a-1)%p != 0]

def lifted_residue(p, a, n):
    assert ZZ(p).is_prime() and 0 <= a < p
    assert (a**3-a-1)%p == 0 and (3*a*a-1)%p != 0
    exponent, u = 1, a
    while exponent < n:
        exponent = min(2*exponent, n)
        modulus = p**exponent
        u = (u - (u**3-u-1)*pow(3*u*u-1, -1, modulus))%modulus
        assert (u**3-u-1)%modulus == 0
    return u

class PlasticRoots(numberdb.Generator):
    table = 'T839'
    parameters = ('p','k','a')
    type = 'Qp'
    digits = 100
    rigour = 'proven'

    def enumerate(self):
        for p in PRIMES:
            for a in simple_residues(p):
                yield {'p':p,'k':1,'a':a}

    def value(self, params, digits):
        p,k,a = (int(params[name]) for name in self.parameters)
        assert k == 1
        n = target_exponent(p,digits)
        u = lifted_residue(p,a,n)
        value = Qp(p,prec=n,print_mode='terse')(ZZ(u)).add_bigoh(n)
        assert int(value.precision_absolute()) == n
        assert int(value.lift()) == u
        assert int(value.valuation()) == 0
        return value

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--preview',action='store_true')
    parser.add_argument('--publish',action='store_true')
    options = parser.parse_args();g=PlasticRoots()
    if options.publish:
        g.publish(removing=False)
    elif options.preview:
        g.preview()
    else:
        g.verify(sample=None)
