"""Reproduce T770: cyclotomic p-adic pairings at frozen rational points.

Requires full SageMath 10.9 (elliptic curves and p-adics) and numberdb.
Place points.txt next to this file. Sage initialization modules are explicit;
no database of elliptic curves or runtime generator/basis search is used.

    sage -pip install numberdb
    sage -python generate.py             # compute/check locally; no write
    sage -python generate.py --publish   # authorized entry upload to T770

Inputs: pinned Cremona ecdata allgens file, commit
25cec5ecfec8b9f016eb1631ac633194c2bed39f. points.txt is the exact selected
158-line subset (SHA-256 below); ordinary eligibility is recomputed exactly.
Point projective coordinates are ordinary [X:Y:Z] -> (X/Z,Y/Z).
The first rank points retain their source order forever. No E.gens() call.

Method: Sage padic_height uses Harvey's p-integral ordinary sigma, with MTT
sign -2 and Iwasawa log(p)=0. Off-diagonals use polarization with /2.
Absolute working exponent is ceil(digits/log10(p))+24. Sage internally adds
2*v_p(m) before division by m^2. Every output retains exactly
ceil(digits/log10(p)) relative p-adic digits. Production evidence compares
this with working guard 44 and independent PARI de Rham heights at both
precisions. Agreement is heuristic, not a certified implementation proof.
"""
import numberdb.sage as numberdb
# Required initialization for Sage's symbolic log used inside its MW routine.
from sage.symbolic.ring import SR
import sage.symbolic.constants
import sage.functions.all
import sage.calculus.calculus
import sage.rings.polynomial.laurent_polynomial_ring
from sage.rings.rational_field import QQ
from sage.rings.integer_ring import ZZ
from sage.rings.padics.factory import Qp
from sage.schemes.elliptic_curves.constructor import EllipticCurve
from pathlib import Path
import hashlib
import json
import math
import os

POINTS_SHA256 = '049273399057ba95739695c3a848bc2bc1791bee35a4e5d90c8048e11471fc21'
PRIMES = (5, 7, 11, 13)
PARAMETERS = ('N', 'c4', 'c6', 'p', 'i', 'j')

def catalogue():
    raw = Path(__file__).with_name('points.txt').read_bytes()
    assert hashlib.sha256(raw).hexdigest() == POINTS_SHA256
    rows = []
    for line in raw.decode().splitlines():
        a = line.split()
        ainvs = tuple(ZZ(x) for x in a[3].strip('[]').split(','))
        r = int(a[4]); projective = [tuple(ZZ(x) for x in q.strip('[]').split(':')) for q in a[6:]]
        rows.append({'N': int(a[0]), 'label': a[0]+a[1]+a[2], 'ainvs': ainvs,
                     'rank': r, 'points': projective[:r], 'torsion': projective[r:],
                     'torsion_structure': json.loads(a[5]), 'source_line': line})
    assert len(rows) == 158
    return rows

def curve(row):
    E = EllipticCurve(QQ, row['ainvs'])
    pts = [E(QQ(X)/Z, QQ(Y)/Z) for X,Y,Z in row['points']]
    return E, pts

def eligible(E, p):
    return E.discriminant() % p != 0 and E.ap(ZZ(p)) % p != 0

def target(p, digits=100):
    # Establish the integer threshold without a floating-point boundary.
    k = 0
    while ZZ(p)**k < ZZ(10)**int(digits):
        k += 1
    return k

def raw_matrix(E, pts, p, absolute):
    h = E.padic_height(ZZ(p), prec=ZZ(absolute))
    diag = [h(P) for P in pts]
    out = {}
    for i in range(len(pts)):
        for j in range(i, len(pts)):
            out[i+1,j+1] = diag[i] if i == j else (h(pts[i]+pts[j])-diag[i]-diag[j])/ZZ(2)
    return out, h

def retained(a, p, digits=100):
    assert not a.is_zero(), 'A zero ball requires investigation; it is not exact zero.'
    v = ZZ(a.valuation()); n = v+target(p,digits)
    assert a.precision_absolute() >= n, 'Insufficient computed relative precision'
    # val-unit mode keeps the full signed Qp element compact, including v<0.
    K = Qp(ZZ(p),prec=target(p,digits),print_mode='val-unit')
    return K(a.add_bigoh(n))

class Pairings(numberdb.Generator):
    table = 'T770'
    parameters = PARAMETERS
    type = 'Qp'
    digits = 100
    rigour = 'heuristic (agreement-checked)'
    files = ('generate.py','points.txt','checks.py','argument-selection.md')

    def __init__(self):
        self.rows = catalogue()
        self.models = {}
        self.matrices = {}

    def enumerate(self):
        for row in self.rows:
            E, pts = curve(row)
            key = (row['N'],int(E.c4()),int(E.c6()))
            self.models[key] = (row,E,pts)
            for p in PRIMES:
                if eligible(E,p):
                    for i in range(1,len(pts)+1):
                        for j in range(i,len(pts)+1):
                            yield dict(zip(PARAMETERS,key+(p,i,j)))

    def value(self, params, digits):
        key = tuple(int(params[k]) for k in PARAMETERS[:3])
        if key not in self.models:
            list(self.enumerate())
        row,E,pts = self.models[key]
        p,i,j = (int(params[k]) for k in PARAMETERS[3:])
        assert p in PRIMES and eligible(E,p) and 1 <= i <= j <= len(pts)
        mk = key+(p,int(digits))
        if mk not in self.matrices:
            raw,_ = raw_matrix(E,pts,p,target(p,digits)+24)
            self.matrices[mk] = {ij:retained(a,p,digits) for ij,a in raw.items()}
        return self.matrices[mk][i,j]

if __name__ == '__main__':
    import argparse
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--publish',action='store_true')
    args=parser.parse_args()
    g=Pairings()
    if args.publish:
        g.publish()
    else:
        total=0
        for params in g.enumerate():
            a=g.value(params,100);assert a.precision_relative()>=target(params['p']);total+=1
        print(json.dumps({'table':g.table,'entries':total,'curve_prime_objects':len(g.matrices)}))
