"""T838: p-adic roots of the golden-ratio polynomial.

Requires SageMath with p-adics and numberdb (tested Sage 10.9, numberdb 0.1.10).
Install the client with sage -pip install numberdb. Run:
  sage -python generate.py             # compute/compare, no writes
  sage -python generate.py --verify    # compare every stored entry
  sage -python generate.py --publish   # fill this authorized draft only
Configure your own NumberDB key and agent/model provenance outside this file.

Parameters (p,k,a) identify the unique root of x^2-x-1 congruent to a modulo
p^k. Here k=1; p is a prime and a is a simple root residue. Defaults cover all
primes through 29 and every root over them. This is a bounded exploratory
reference selection, not a distinguished prime endpoint. All roots are units:
a nonzero valuation would leave a unique lowest-valuation term in x^2-x-1.

Exact modular Newton iteration doubles the precision exponent. For N minimal
with p^N >= 10^digits, its canonical residue u obeys g(u)=0 mod p^N and g'(u)
is a unit. Hensel's lemma (Conrad, Theorem 2.1) proves a unique root in this
ball. The returned Sage Qp object carries precisely O(p^N), not an exact
integer or real decimal accuracy. No floating-point arithmetic is used.
"""
import argparse
import numberdb.sage as numberdb
from sage.rings.integer_ring import ZZ
from sage.rings.padics.factory import Qp

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


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


def newton_residue(p, a, n):
    if not ZZ(p).is_prime() or not (0 <= a < p):
        raise ValueError('Require a prime and canonical residue')
    if (a*a-a-1) % p or (2*a-1) % p == 0:
        raise ValueError('The branch must be a simple root modulo p')
    u, e = int(a), 1
    while e < n:
        e = min(2*e, n)
        modulus = int(p) ** e
        u = (u - (u*u-u-1)*pow(2*u-1, -1, modulus)) % modulus
    assert (u*u-u-1) % (p**n) == 0 and u % p == a
    return u


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

    def enumerate(self):
        for p in BASE_PRIMES:
            for a in range(p):
                if (a*a-a-1) % p == 0 and (2*a-1) % p != 0:
                    yield {'p': p, 'k': 1, 'a': a}

    def value(self, params, digits):
        p, k, a = (int(params[name]) for name in self.parameters)
        if k != 1:
            raise ValueError('k is the distinguishing precision and must be 1')
        n = target_exponent(p, digits)
        u = newton_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 and value.valuation() == 0
        return value


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