"""T773: Néron–Tate pairings of the frozen ecdata points.

Save generate.py and points.json from this table's attachments together.
Install a full SageMath or the elliptic-curve components of passagemath, and
numberdb (`sage -pip install numberdb`). Run `sage -python generate.py` to check all stored entries (read only),
or `sage -python generate.py --publish` to fill an authorized target draft.
The account key and engine/model/run provenance belong in the environment.

The point indices are the original free-generator order in ecdata commit
25cec5ecfec8b9f016eb1631ac633194c2bed39f, not software-generated lift order.
The source-reported basis claim is not an independently certified index.
All upper-triangular pairings are included for source curve number 1 with
rank 1 and N<=175, rank 2 and N<=2000, or rank>=3 and N<=10000.

PARI ellheight(E,P,Q) has the larger Cremona/BSD normalization and preserves
signed off-diagonal entries. We compare working decimal precisions digits+100
and digits+200 (681 and 1013 bits at digits=100, including the client's 16-bit
guard). The returned union is heuristic agreement evidence, not a rigorous
rounding enclosure for the mathematical height. checks.py uses Sage's separate
non-archimedean and archimedean local-height implementation, bypassing the
algorithm-insensitive Point.height cache. Both routes share exact Sage/PARI
arithmetic and curve local data; they are not independent arithmetic stacks.
"""
import argparse
from functools import lru_cache
import hashlib
import json
from pathlib import Path

import numberdb.sage as numberdb
from sage.rings.rational_field import QQ
from sage.rings.real_mpfr import RealField
from sage.schemes.elliptic_curves.constructor import EllipticCurve
from sage.libs.pari import pari

POINTS_SHA256 = '55a268208385a1eb47d1feeb2853cc6fd41c0aab6d11dc47307bec836051127b'

@lru_cache(None)
def roster():
    raw = Path(__file__).with_name('points.json').read_bytes()
    if hashlib.sha256(raw).hexdigest() != POINTS_SHA256:
        raise ValueError('The frozen point catalogue hash differs')
    return json.loads(raw)

@lru_cache(None)
def curve(key):
    record = next(r for r in roster() if (r['N'], r['c4'], r['c6']) == key)
    E = EllipticCurve(QQ, record['ainvs'])
    points = [E([QQ(p[0])/QQ(p[2]), QQ(p[1])/QQ(p[2])])
              for p in record['projective']]
    return E, points

@lru_cache(None)
def pari_curve(key, precision):
    E, _ = curve(key)
    return pari(list(E.a_invariants())).ellinit()

def pairing(params, precision):
    key = tuple(int(params[k]) for k in ('N', 'c4', 'c6'))
    _, points = curve(key)
    i, j = int(params['i']), int(params['j'])
    if not 1 <= i <= j <= len(points):
        raise ValueError('Point indices must satisfy 1 <= i <= j <= r')
    P, Q = points[i-1], points[j-1]
    e = pari_curve(key, precision)
    return RealField(precision)(e.ellheight(P, Q, precision=precision))

class HeightPairings(numberdb.Generator):
    table = 'T773'
    parameters = ('N', 'c4', 'c6', 'i', 'j')
    type = 'R'
    digits = 100
    rigour = 'heuristic (agreement-checked)'

    def enumerate(self):
        for r in roster():
            for i in range(1, r['source_rank']+1):
                for j in range(i, r['source_rank']+1):
                    yield dict(N=r['N'], c4=r['c4'], c6=r['c6'], i=i, j=j)

    def value(self, params, digits):
        return numberdb.agreeing(
            lambda working: str(pairing(params, numberdb.bits(working))),
            at=(digits+100, digits+200))

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--publish', action='store_true')
    args = parser.parse_args()
    g = HeightPairings()
    print(g.publish() if args.publish else g.verify(sample=None))
