/*
 * // Copyright (c) Radzivon Bartoshyk 7/2025. All rights reserved.
 * //
 * // Redistribution and use in source and binary forms, with or without modification,
 * // are permitted provided that the following conditions are met:
 * //
 * // 1.  Redistributions of source code must retain the above copyright notice, this
 * // list of conditions and the following disclaimer.
 * //
 * // 2.  Redistributions in binary form must reproduce the above copyright notice,
 * // this list of conditions and the following disclaimer in the documentation
 * // and/or other materials provided with the distribution.
 * //
 * // 3.  Neither the name of the copyright holder nor the names of its
 * // contributors may be used to endorse or promote products derived from
 * // this software without specific prior written permission.
 * //
 * // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
use crate::bessel::i0f::i0f_small;
use crate::bessel::j0f::j1f_rsqrt;
use crate::common::f_fmla;
use crate::exponents::core_expf;
use crate::logs::fast_logf;
use crate::polyeval::{f_estrin_polyeval7, f_estrin_polyeval8};

/// Modified exponentially scaled Bessel of the first kind of order 0
///
/// Computes K0(x)exp(x)
///
/// Max ULP 0.5
pub fn f_k0ef(x: f32) -> f32 {
    let ux = x.to_bits();
    if ux >= 0xffu32 << 23 || ux == 0 {
        // |x| == 0, |x| == inf, |x| == NaN, x < 0
        if ux.wrapping_shl(1) == 0 {
            // |x| == 0
            return f32::INFINITY;
        }
        if x.is_infinite() {
            return if x.is_sign_positive() { 0. } else { f32::NAN };
        }
        return x + f32::NAN; // x == NaN
    }

    let xb = x.to_bits();

    if xb <= 0x3f800000u32 {
        // x <= 1.0
        if xb <= 0x34000000u32 {
            // |x| <= f32::EPSILON
            // taylor series for K0(x)exp(x) ~ (-euler_gamma + log(2) - log(x)) + (-euler_gamma + log(2) - log(x)) * x
            let dx = x as f64;
            let log_x = fast_logf(x);
            const M_EULER_GAMMA_P_LOG2: f64 = f64::from_bits(0x3fbdadb014541eb2);
            let c1 = -log_x + M_EULER_GAMMA_P_LOG2;
            return f_fmla(c1, dx, c1) as f32;
        }
        return k0ef_small(x);
    }

    k0ef_asympt(x)
}

/**
K0(x) + log(x) * I0(x) = P(x^2)
hence
K0(x) = P(x^2) - log(x)*I0(x)

Polynomial generated by Wolfram Mathematica:
```text
<<FunctionApproximations`
ClearAll["Global`*"]
f[x_]:=BesselK[0,x]+Log[x]BesselI[0,x]
g[z_]:=f[Sqrt[z]]
{err, approx}=MiniMaxApproximation[g[z],{z,{0.000000001,1},6,0},WorkingPrecision->60]
poly=Numerator[approx][[1]];
coeffs=CoefficientList[poly,z];
TableForm[Table[Row[{"'",NumberForm[coeffs[[i+1]],{50,50}, ExponentFunction->(Null&)],"',"}],{i,0,Length[coeffs]-1}]]
```
**/
#[inline]
fn k0ef_small(x: f32) -> f32 {
    let v_log = fast_logf(x);
    let i0 = i0f_small(x);

    let v_exp = core_expf(x);

    let dx = x as f64;

    let p = f_estrin_polyeval7(
        dx * dx,
        f64::from_bits(0x3fbdadb014541ece),
        f64::from_bits(0x3fd1dadb01453e9c),
        f64::from_bits(0x3f99dadb01491ac7),
        f64::from_bits(0x3f4bb90e82a4f609),
        f64::from_bits(0x3eef4749ebd25b10),
        f64::from_bits(0x3e85d5b5668593af),
        f64::from_bits(0x3e15233b0788618b),
    );
    let c = f_fmla(-i0, v_log, p);
    (c * v_exp) as f32
}

/**
Generated in Wolfram

Computes sqrt(x)*exp(x)*K0(x)=Pn(1/x)/Qm(1/x)
hence
K0(x)exp(x) = Pn(1/x)/Qm(1/x) / sqrt(x)

```text
<<FunctionApproximations`
ClearAll["Global`*"]
f[x_]:=Sqrt[x] Exp[x] BesselK[0,x]
g[z_]:=f[1/z]
{err,approx}=MiniMaxApproximation[g[z],{z,{2^-33,1},7,7},WorkingPrecision->60]
poly=Numerator[approx][[1]];
coeffs=CoefficientList[poly,z];
TableForm[Table[Row[{"'",NumberForm[coeffs[[i+1]],{50,50},ExponentFunction->(Null&)],"',"}],{i,0,Length[coeffs]-1}]]
poly=Denominator[approx][[1]];
coeffs=CoefficientList[poly,z];
TableForm[Table[Row[{"'",NumberForm[coeffs[[i+1]],{50,50},ExponentFunction->(Null&)],"',"}],{i,0,Length[coeffs]-1}]]
```
**/
#[inline]
fn k0ef_asympt(x: f32) -> f32 {
    let dx = x as f64;
    let recip = 1. / dx;
    let r_sqrt = j1f_rsqrt(dx);

    let p_num = f_estrin_polyeval8(
        recip,
        f64::from_bits(0x3ff40d931ff62701),
        f64::from_bits(0x402d8410a60e2ced),
        f64::from_bits(0x404e9f18049bf704),
        f64::from_bits(0x405c07682282783c),
        f64::from_bits(0x4057379c68ce6d5e),
        f64::from_bits(0x403ffd64a0105c4e),
        f64::from_bits(0x400cc53ed67913b4),
        f64::from_bits(0x3faf8cc8747a5d72),
    );
    let p_den = f_estrin_polyeval8(
        recip,
        f64::from_bits(0x3ff0000000000000),
        f64::from_bits(0x4027ccde1d0eeb14),
        f64::from_bits(0x40492418133aa7a7),
        f64::from_bits(0x4057be8a004d0938),
        f64::from_bits(0x4054cc77d1dfef26),
        f64::from_bits(0x403fd2187097af1d),
        f64::from_bits(0x4011c77649649e55),
        f64::from_bits(0x3fc2080a5965ef9b),
    );
    let v = p_num / p_den;
    let pp = v * r_sqrt;
    pp as f32
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_k0f() {
        assert_eq!(f_k0ef(2.034804e-5), 10.918679);
        assert_eq!(f_k0ef(0.010260499), 4.743962);
        assert_eq!(f_k0ef(0.3260499), 1.7963701);
        assert_eq!(f_k0ef(0.72341), 1.3121376);
        assert_eq!(f_k0ef(0.), f32::INFINITY);
        assert_eq!(f_k0ef(-0.), f32::INFINITY);
        assert!(f_k0ef(-0.5).is_nan());
        assert!(f_k0ef(f32::NEG_INFINITY).is_nan());
        assert_eq!(f_k0ef(f32::INFINITY), 0.);
    }
}
