"""Rigid hypergeometric Calabi–Yau Frobenius polynomials, numberdb.org/T764.

SageMath 10.9 (or compatible), numberdb >=0.1.10:
    sage -pip install numberdb
    sage -python generate.py                 # verify all stored entries
    sage -python generate.py --preview       # preview comparisons without writes
    sage -python generate.py --publish       # fill authorized private draft
    sage -python checks.py                   # independent checks

Private-draft reads (including verify and preview) need the author's API key.
The default selection is all fourteen classified cyclotomic templates at every
prime 7<=p<=31, in the order listed below. The mathematical domain includes
every prime unramified for the rigid rank-two constituent. This implementation
uses Theorem 1 of Long–Tu–Yui–Zudilin, arXiv:1705.01663v4, so evaluates p>5.
It reconstructs the signed integer a_p from the truncated exact rational
hypergeometric sum modulo p^3, using a_p^2<=4*p^3. Since p^6>16*p^3, at most
one integer in the Weil interval has that residue. No floating point, unit-root
substitution, quadratic twist or numerical precision assumption is involved.
The source's Theorem 2 separates off the singular stalk's extra character.
Checks use exact newform arithmetic and a separately implemented Gauss sum.
"""
import os
import sys
from functools import lru_cache
import numberdb.sage as numberdb
from sage.rings.integer_ring import ZZ
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing

R = PolynomialRing(ZZ, 'T')
T = R.gen()
TEMPLATES = ('2.2.2.2','2.2.3','2.2.4','2.2.6','3.3','3.4','3.6',
             '4.4','4.6','6.6','5','8','10','12')
CONDUCTORS = dict(zip(TEMPLATES,(8,36,16,72,27,9,108,32,144,216,25,128,200,864)))
PRIMES = (7,11,13,17,19,23,29,31)

@lru_cache(None)
def upper_parameters(template):
    if template not in TEMPLATES:
        raise ValueError('Unknown classified template')
    pairs = tuple((ZZ(j),ZZ(d)) for d in map(int,template.split('.'))
                  for j in range(1,d) if ZZ(j).gcd(d)==1)
    assert len(pairs)==4
    return pairs

@lru_cache(None)
def trace(template,p):
    p=ZZ(p)
    alpha=upper_parameters(template)
    if not p.is_prime(proof=True) or CONDUCTORS[template] % p == 0:
        raise ValueError('Require an unramified rational prime')
    if p<=5:
        raise NotImplementedError('This exact recovery theorem requires p>5')
    modulus=p**3
    term=total=ZZ(1)
    for n in range(int(p)-1):
        for j,d in alpha:
            assert d % p
            term=(term*(j+d*n)*d.inverse_mod(modulus)) % modulus
        term=(term*ZZ(n+1).inverse_mod(modulus)**4) % modulus
        total=(total+term) % modulus
    a=total if 2*total<=modulus else total-modulus
    assert modulus**2>16*p**3
    assert a*a<=4*p**3, (template,p,a)
    assert type(a).__name__=='Integer'
    return a

class RigidFrobenius(numberdb.Generator):
    table='T764'
    parameters=('template','p')
    type='Z[]'
    rigour='exact'
    files=('generate.py','checks.py','newform-reference.json',
           'argument-selection.md','numerical-evidence.md','skill-evidence.json')

    def enumerate(self):
        for template in TEMPLATES:
            for p in PRIMES:
                yield {'template':template,'p':str(p)}

    def value(self,params,digits=100):
        p=ZZ(params['p'])
        return R([1,-trace(params['template'],p),p**3])

if __name__=='__main__':
    if os.environ.get('NUMBERDB_KEY_FROM_STDIN')=='1':
        os.environ['NUMBERDB_API_KEY']=sys.stdin.read().strip()
    gen=RigidFrobenius()
    if '--publish' in sys.argv or os.environ.get('NUMBERDB_PUBLISH')=='1':
        print(gen.publish(message=os.environ.get('NUMBERDB_EDIT_MESSAGE','Fill exact rigid Frobenius polynomials'),removing=False))
    elif '--preview' in sys.argv:
        print(gen.preview())
    else:
        report=gen.verify(sample=None)
        print(report)
        sys.exit(0 if report.ok else 1)
