"""Primitive odd modular periods of rational newforms -- numberdb.org/T766.

Install SageMath and numberdb; keep forms.py beside this file:
    sage -pip install numberdb
    sage -python generate.py              # verify all stored entries
    sage -python generate.py --publish    # upload to this existing draft

For the integral r_f(X)=integral_0^(i infinity) f(tau)(tau-X)^(k-2) d tau,
its odd part is Omega_f^-*P_f^-(X), where P is primitive in Z[X] with
positive leading coefficient. All forms have trivial character, rational
Fourier coefficients and a_1=1. Parameter i is ordered among ALL embedded
newforms before filtering to rational forms. Signs are preserved.

PARI's direct mfperiodpol is evaluated at 160 and 220 decimal working digits
(for 100 output digits), with an additional 32-bit guard. Agreement defines a
heuristic interval, not a certified error bound. checks.py implements a
separate split Mellin computation from Sage's exact Fourier coefficients,
with explicit tail estimates. See argument-selection.md and research.md.
Credentials and upload attribution are supplied by the calling environment.
"""
import os,sys,json
from pathlib import Path
from functools import lru_cache
from fractions import Fraction
import numberdb.sage as numberdb
from numberdb._write import to_text
from sage.libs.pari import pari
from sage.rings.rational_field import QQ
from sage.rings.real_mpfr import RealField
from sage.rings.complex_mpfr import ComplexField
from forms import selected_spaces,space_data,exact_polynomial,roster

@lru_cache(None)
def pari_form(N,k,i):
    r=space_data(N,k)[3][i-1]
    if r['field_degree']!=1:raise ValueError('The Hecke field must be rational')
    B=r['sturm_bound'];expected=[QQ(c) for c in r['q'].padded_list(B+1)]
    mf=pari.mfinit([N,k],0);matches=[]
    for f in pari.mfeigenbasis(mf):
        try:coeff=[QQ(c) for c in pari.mfcoefs(f,B)]
        except (TypeError,ValueError):continue
        if coeff==expected:matches.append(f)
    if len(matches)!=1:raise ValueError('Fourier identification through the Sturm bound failed')
    return mf,matches[0]

@lru_cache(None)
def scalar_at(N,k,i,working):
    mf,f=pari_form(N,k,i);p=exact_polynomial(N,k,i);w=k-2
    bits=numberdb.bits(working,losing=32)
    pari.set_real_precision(working+12)
    C=ComplexField(bits);R=RealField(bits)
    raw=pari.mfperiodpol(mf,f,-1,precision=bits)
    c=[C(pari.polcoef(raw,j)) for j in range(w+1)]
    j=int(p.degree())
    omega=c[j].real()/R(p[j])
    if omega.is_NaN() or omega.is_infinity() or omega==0:raise ValueError('Nonfinite or zero scale')
    relative=max(abs(c[j]-C(omega*R(p[j]))) for j in range(w+1))/max(abs(a) for a in c)
    if relative>R(10)**(-working+20):raise ValueError('Direct period is inconsistent with exact shape')
    return omega

def display_value(value,digits):
    return to_text(value,digits=digits)

class PrimitiveOddPeriods(numberdb.Generator):
    table='T766'
    parameters=('N','k','i')
    type='R'
    digits=100
    rigour='heuristic (agreement-checked)'
    files=('generate.py','forms.py','checks.py','argument-selection.md','research.md',
           'roster.json','numerical-evidence.json','manifest.json','source-hashes.json',
           'dependency-versions.json','check.py','dry_run.py')
    def enumerate(self):
        for r in roster():
            if r['field_degree']==1:
                yield dict(N=r['N'],k=r['k'],i=r['i'])
    def all_entries(self,digits=None,**bounds):
        digits=self.digits if digits is None else digits
        for params in self.enumerate():
            yield params,display_value(self.value(params,digits),digits)
    def value(self,params,digits):
        N,k,i=(int(params[key]) for key in ('N','k','i'))
        # The offsets are fixed and explicit; no precision escalation on failure.
        scalar=numberdb.agreeing(lambda working:scalar_at(N,k,i,working),at=(digits+60,digits+120))
        scalar=numberdb.RealInterval(Fraction(str(QQ(scalar.lower()))),Fraction(str(QQ(scalar.upper()))))
        return scalar

if __name__=='__main__':
    g=PrimitiveOddPeriods()
    if '--sample' in sys.argv:
        v=g.value(dict(N=1,k=12,i=1),100)
        print('SAMPLE '+display_value(v,100),flush=True)
    elif '--publish' in sys.argv or os.environ.get('NUMBERDB_PUBLISH')=='1':
        if os.environ.get('NUMBERDB_KEY_FROM_STDIN')=='1':os.environ['NUMBERDB_API_KEY']=sys.stdin.read().strip()
        message=os.environ.get('NUMBERDB_INITIAL_MESSAGE','Fill checked primitive odd periods')
        print(g.publish(message=message,removing=False))
    else:
        report=g.verify(sample=None);print(report);sys.exit(0 if report.ok else 1)
