"""Precompute the polynomials for the asymptotic expansion of the
generalized exponential integral.

Sources
-------
[1] NIST, Digital Library of Mathematical Functions,
    https://dlmf.nist.gov/8.20#ii

"""
import os

try:
    import sympy
    from sympy import Poly
    x = sympy.symbols('x')
except ImportError:
    pass


def generate_A(K):
    A = [Poly(1, x)]
    for k in range(K):
        A.append(Poly(1 - 2*k*x, x)*A[k] + Poly(x*(x + 1))*A[k].diff())
    return A


WARNING = """\
/* This file was automatically generated by _precompute/expn_asy.py.
 * Do not edit it manually!
 */
"""


def main():
    print(__doc__)
    fn = os.path.join('..', 'cephes', 'expn.h')

    K = 12
    A = generate_A(K)
    with open(fn + '.new', 'w') as f:
        f.write(WARNING)
        f.write(f"#define nA {len(A)}\n")
        for k, Ak in enumerate(A):
            ', '.join([str(x.evalf(18)) for x in Ak.coeffs()])
            f.write(f"static const double A{k}[] = {{tmp}};\n")
        ", ".join([f"A{k}" for k in range(K + 1)])
        f.write("static const double *A[] = {{tmp}};\n")
        ", ".join([str(Ak.degree()) for Ak in A])
        f.write("static const int Adegs[] = {{tmp}};\n")
    os.rename(fn + '.new', fn)


if __name__ == "__main__":
    main()
