/*
     Description: ContinuedFraction

     Copyright : All right reserved by ICT

     Author : Zhang Zhonghai
     Date : 2025/12/25
*/
#pragma once

#include <math.h>

#include <functional>
#include <iostream>

#include "math_const.h"
#include "precision.h"

//using ContinuedFractionGetFunc = std::function<double(int, double)>();
// using ContinuedFractionGetFunc = double (*)(int n, double x);

struct ContinuedFraction {
    /** Maximum allowed numerical error. */
    static constexpr double DEFAULT_EPSILON = 10e-9;

    // ContinuedFraction(ContinuedFractionGetFunc _getA, ContinuedFractionGetFunc _getB) {
    //     getA = _getA;
    //     getB = _getB;
    // }
    /**
     * Access the n-th a coefficient of the continued fraction.  Since a can be
     * a function of the evaluation point, x, that is passed in as well.
     * @param n the coefficient index to retrieve.
     * @param x the evaluation point.
     * @return the n-th a coefficient.
     */
    //ContinuedFractionGetFunc getA;
    virtual double getA(int n, double x) = 0;

    /**
     * Access the n-th b coefficient of the continued fraction.  Since b can be
     * a function of the evaluation point, x, that is passed in as well.
     * @param n the coefficient index to retrieve.
     * @param x the evaluation point.
     * @return the n-th b coefficient.
     */
    //ContinuedFractionGetFunc getB;
    virtual double getB(int n, double x) = 0;

    /**
     * Evaluates the continued fraction at the value x.
     * @param x the evaluation point.
     * @return the value of the continued fraction evaluated at x.
     * @throws ConvergenceException if the algorithm fails to converge.
     */
    double evaluate(double x) { return evaluate(x, DEFAULT_EPSILON, MathConst::INT_MAX_VALUE); }

    /**
     * Evaluates the continued fraction at the value x.
     * @param x the evaluation point.
     * @param epsilon maximum error allowed.
     * @return the value of the continued fraction evaluated at x.
     * @throws ConvergenceException if the algorithm fails to converge.
     */
    double evaluate(double x, double epsilon) { return evaluate(x, epsilon, MathConst::INT_MAX_VALUE); }

    /**
     * Evaluates the continued fraction at the value x.
     * @param x the evaluation point.
     * @param maxIterations maximum number of convergents
     * @return the value of the continued fraction evaluated at x.
     * @throws ConvergenceException if the algorithm fails to converge.
     * @throws MaxCountExceededException if maximal number of iterations is reached
     */
    double evaluate(double x, int maxIterations) {
        return evaluate(x, DEFAULT_EPSILON, maxIterations);
    }

    /**
     * Evaluates the continued fraction at the value x.
     * <p>
     * The implementation of this method is based on the modified Lentz algorithm as described
     * on page 18 ff. in:
     * <ul>
     *   <li>
     *   I. J. Thompson,  A. R. Barnett. "Coulomb and Bessel Functions of Complex Arguments and Order."
     *   <a target="_blank" href="http://www.fresco.org.uk/papers/Thompson-JCP64p490.pdf">
     *   http://www.fresco.org.uk/papers/Thompson-JCP64p490.pdf</a>
     *   </li>
     * </ul>
     * <b>Note:</b> the implementation uses the terms a<sub>i</sub> and b<sub>i</sub> as defined in
     * <a href="http://mathworld.wolfram.com/ContinuedFraction.html">Continued Fraction @ MathWorld</a>.
     * </p>
     *
     * @param x the evaluation point.
     * @param epsilon maximum error allowed.
     * @param maxIterations maximum number of convergents
     * @return the value of the continued fraction evaluated at x.
     * @throws ConvergenceException if the algorithm fails to converge.
     * @throws MaxCountExceededException if maximal number of iterations is reached
     */
    double evaluate(double x, double epsilon, int maxIterations) {
        const double small = 1e-50;
        double hPrev = getA(0, x);

        // use the value of small as epsilon criteria for zero checks
        if (Precision::equals(hPrev, 0.0, small)) {
            hPrev = small;
        }

        int n = 1;
        double dPrev = 0.0;
        double cPrev = hPrev;
        double hN = hPrev;

        while (n < maxIterations) {
            const double a = getA(n, x);
            const double b = getB(n, x);

            double dN = a + b * dPrev;
            if (Precision::equals(dN, 0.0, small)) {
                dN = small;
            }
            double cN = a + b / cPrev;
            if (Precision::equals(cN, 0.0, small)) {
                cN = small;
            }

            dN = 1 / dN;
            const double deltaN = cN * dN;
            hN = hPrev * deltaN;

            if (std::isinf(hN)) {
                std::cerr << "ConvergenceException INFINITY" << std::endl;
                exit(1);
                // throw new ConvergenceException(LocalizedFormats.CONTINUED_FRACTION_INFINITY_DIVERGENCE, x);
            }
            if (std::isnan(hN)) {
                std::cerr << "ConvergenceException NAN" << std::endl;
                exit(1);
                // throw new ConvergenceException(LocalizedFormats.CONTINUED_FRACTION_NAN_DIVERGENCE, x);
            }

            if (std::abs(deltaN - 1.0) < epsilon) {
                break;
            }

            dPrev = dN;
            cPrev = cN;
            hPrev = hN;
            n++;
        }

        if (n >= maxIterations) {
            std::cerr << "MaxCountExceededException max iterations" << std::endl;
            exit(1);
            // throw new MaxCountExceededException(LocalizedFormats.NON_CONVERGENT_CONTINUED_FRACTION, maxIterations, x);
        }

        return hN;
    }
};