"""Generalized Okamoto polynomials -- numberdb.org/T559.

Run with SageMath:
    sage -pip install numberdb
    sage -python generate.py                  # verify every stored entry
    sage -python generate.py --fill           # fill the existing draft

The --fill action requires NUMBERDB_API_KEY and writes entries and attachments;
it does not offer or publish the draft. For a piped key, set
NUMBERDB_KEY_FROM_STDIN=1; NUMBERDB_PUBLISH=1 is an equivalent fill switch.

Physicists' Hermite polynomials are built in QQ[x] by their three-term
recurrence. A fraction-free determinant and its explicit Vandermonde leading
coefficient give the monic Wronskian, without variable rescaling. All divisions
are exact Sage polynomial divisions or divisions of Sage rationals. The
selection and its practical degree bound are explained in argument-selection.md.
"""
import os
import re
import sys
from functools import lru_cache

import numberdb.sage as numberdb
from sage.rings.rational_field import QQ
from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing

R = PolynomialRing(QQ, 'x')
x = R.gen()
MAX_DEGREE = 60


def degree(m, n):
    return m*m + n*n - m*n + n


def degree_list(m, n):
    return tuple(3*j+1 for j in range(m)) + tuple(3*j+2 for j in range(n))


@lru_cache(None)
def hermite(k):
    if k == 0:
        return R.one()
    if k == 1:
        return 2*x
    return 2*x*hermite(k-1) - 2*(k-1)*hermite(k-2)


def exact_det(rows):
    """Bareiss elimination, with pivoting and every remainder checked."""
    count = len(rows)
    if count == 0:
        return R.one()
    a = [[R(v) for v in row] for row in rows]
    sign = 1
    previous = R.one()
    for k in range(count-1):
        pivot_row = next((j for j in range(k,count) if a[j][k]), None)
        if pivot_row is None:
            return R.zero()
        if pivot_row != k:
            a[k], a[pivot_row] = a[pivot_row], a[k]
            sign = -sign
        pivot = a[k][k]
        for i in range(k+1,count):
            for j in range(k+1,count):
                numerator = pivot*a[i][j] - a[i][k]*a[k][j]
                quotient, remainder = numerator.quo_rem(previous)
                if remainder:
                    raise ArithmeticError('inexact Bareiss division')
                a[i][j] = quotient
        for i in range(k+1,count):
            a[i][k] = R.zero()
        previous = pivot
    return sign*a[-1][-1]


@lru_cache(None)
def okamoto(m, n):
    if m < 0 or n < 0:
        raise ValueError('both indices must be nonnegative')
    degrees = degree_list(m,n)
    factors = [hermite(k) for k in degrees]
    determinant = exact_det([[f.derivative(i) for f in factors]
                             for i in range(len(factors))])
    leading = QQ(2)**sum(degrees)
    for j, kj in enumerate(degrees):
        for ki in degrees[:j]:
            leading *= kj-ki
    if determinant.leading_coefficient() != leading:
        raise ArithmeticError('Wronskian leading coefficient disagrees')
    result = R([c/leading for c in determinant.list()])
    assert result.degree() == degree(m,n)
    assert result.leading_coefficient() == 1
    return result


class GeneralizedOkamoto(numberdb.Generator):
    table = 'T559'
    parameters = ('m','n')
    type = 'Q[]'
    rigour = 'exact'
    digits = 100  # Exact polynomial coefficients need no decimal approximation.
    files = ('generate.py', 'checks.py', 'argument-selection.md',
             'numerical-evidence.md', 'skill-manifest.json')

    def enumerate(self, max_degree=MAX_DEGREE):
        # d >= 3*m^2/4 and d >= 3*n^2/4, so this finite search is exhaustive.
        bound = 0
        while 3*bound*bound <= 4*max_degree:
            bound += 1
        pairs = [(m,n) for m in range(bound+1) for n in range(bound+1)
                 if degree(m,n) <= max_degree]
        for m,n in sorted(pairs, key=lambda p:(degree(*p),p[0],p[1])):
            yield {'m':m,'n':n}

    def value(self, params, digits):
        return okamoto(int(params['m']),int(params['n']))


if __name__ == '__main__':
    if os.environ.get('NUMBERDB_KEY_FROM_STDIN') == '1':
        key = sys.stdin.read().strip()
        if re.match(r'^[A-Z_][A-Z0-9_]*\s*=', key):
            key=key.split('=',1)[1].strip().strip('\"\'')
        numberdb.configure(api_key=key)
    generator = GeneralizedOkamoto()
    if '--fill' in sys.argv or os.environ.get('NUMBERDB_PUBLISH') == '1':
        print(generator.publish(message='Fill exact monic Okamoto polynomials after independent checks'))
    else:
        report=generator.verify(sample=None)
        print(report)
        sys.exit(0 if report.ok else 1)
