/*
 * // Copyright (c) Radzivon Bartoshyk 8/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::common::f_fmla;
use crate::polyeval::{f_polyeval3, f_polyeval5};
use crate::sin_cosf::sincosf_eval::sincosf_eval;

#[inline(always)]
fn cscf_gen_impl(x: f32) -> f32 {
    let x_abs = x.to_bits() & 0x7fff_ffffu32;
    let xd = x as f64;

    // |x| <= pi/16
    if x_abs <= 0x3e49_0fdbu32 {
        // |x| < 0.000443633
        if x_abs < 0x39e8_9769u32 {
            if x_abs == 0u32 {
                // For signed zeros.
                return if x.is_sign_negative() {
                    f32::NEG_INFINITY
                } else {
                    f32::INFINITY
                };
            }
            let dx = x as f64;
            let c_term = 1. / dx;
            let x2 = dx * dx;
            // Maclaurin series
            // 1/x + x/6 + (7 x^3)/360 + (31 x^5)/15120 + O(x^7)
            let p = f_polyeval3(
                x2,
                f64::from_bits(0x3fc5555555555555),
                f64::from_bits(0x3f93e93e93e93e94),
                f64::from_bits(0x3f60b2463814bc5f),
            );
            return f_fmla(dx, p, c_term) as f32;
        }

        let xsqr = xd * xd;

        /*
        Generated by Sollya:
        f = 1 / sin(x) - 1/x;

        d = [0.000443633; pi/16];
        pf = fpminimax(f, [|1, 3, 5, 7, 9|], [|D...|], d, relative, floating);

        See ./notes/cscf.sollya
         */

        let p = f_polyeval5(
            xsqr,
            f64::from_bits(0x3fc5555555555562),
            f64::from_bits(0x3f93e93e93e730a3),
            f64::from_bits(0x3f60cbb77382ae6f),
            f64::from_bits(0x3f2b85bfd4188934),
            f64::from_bits(0x3ef697a32ebe822d),
        );
        return f_fmla(xd, p, 1. / xd) as f32;
    }

    if x_abs >= 0x7f80_0000u32 {
        return x + f32::NAN;
    }

    // Formula:
    //   sin(x) = sin((k + y)*pi/32)
    //          = sin(y*pi/32) * cos(k*pi/32) + cos(y*pi/32) * sin(k*pi/32)
    // The values of sin(k*pi/32) and cos(k*pi/32) for k = 0..31 are precomputed
    // and stored using a vector of 32 doubles. Sin(y*pi/32) and cos(y*pi/32) are
    // computed using degree-7 and degree-6 minimax polynomials generated by
    // Sollya respectively.

    let rs = sincosf_eval(xd, x_abs);
    (1. / f_fmla(rs.sin_y, rs.cos_k, f_fmla(rs.cosm1_y, rs.sin_k, rs.sin_k))) as f32
}

#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
#[target_feature(enable = "avx", enable = "fma")]
unsafe fn cscf_fma_impl(x: f32) -> f32 {
    let x_abs = x.to_bits() & 0x7fff_ffffu32;
    let xd = x as f64;

    // |x| <= pi/16
    if x_abs <= 0x3e49_0fdbu32 {
        // |x| < 0.000443633
        if x_abs < 0x39e8_9769u32 {
            if x_abs == 0u32 {
                // For signed zeros.
                return if x.is_sign_negative() {
                    f32::NEG_INFINITY
                } else {
                    f32::INFINITY
                };
            }
            let dx = x as f64;
            let c_term = 1. / dx;
            let x2 = dx * dx;
            // Maclaurin series
            // 1/x + x/6 + (7 x^3)/360 + (31 x^5)/15120 + O(x^7)
            use crate::polyeval::d_polyeval3;
            let p = d_polyeval3(
                x2,
                f64::from_bits(0x3fc5555555555555),
                f64::from_bits(0x3f93e93e93e93e94),
                f64::from_bits(0x3f60b2463814bc5f),
            );
            return f64::mul_add(dx, p, c_term) as f32;
        }

        let xsqr = xd * xd;

        /*
        Generated by Sollya:
        f = 1 / sin(x) - 1/x;

        d = [0.000443633; pi/16];
        pf = fpminimax(f, [|1, 3, 5, 7, 9|], [|D...|], d, relative, floating);

        See ./notes/cscf.sollya
         */
        use crate::polyeval::d_polyeval5;
        let p = d_polyeval5(
            xsqr,
            f64::from_bits(0x3fc5555555555562),
            f64::from_bits(0x3f93e93e93e730a3),
            f64::from_bits(0x3f60cbb77382ae6f),
            f64::from_bits(0x3f2b85bfd4188934),
            f64::from_bits(0x3ef697a32ebe822d),
        );
        return f64::mul_add(xd, p, 1. / xd) as f32;
    }

    if x_abs >= 0x7f80_0000u32 {
        return x + f32::NAN;
    }

    // Formula:
    //   sin(x) = sin((k + y)*pi/32)
    //          = sin(y*pi/32) * cos(k*pi/32) + cos(y*pi/32) * sin(k*pi/32)
    // The values of sin(k*pi/32) and cos(k*pi/32) for k = 0..31 are precomputed
    // and stored using a vector of 32 doubles. Sin(y*pi/32) and cos(y*pi/32) are
    // computed using degree-7 and degree-6 minimax polynomials generated by
    // Sollya respectively.
    use crate::sin_cosf::sincosf_eval::sincosf_eval_fma;
    let rs = sincosf_eval_fma(xd, x_abs);
    (1. / f64::mul_add(
        rs.sin_y,
        rs.cos_k,
        f64::mul_add(rs.cosm1_y, rs.sin_k, rs.sin_k),
    )) as f32
}

/// Cosecant ( 1 / sin(x) )
///
/// ULP 0.5
#[inline]
pub fn f_cscf(x: f32) -> f32 {
    #[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
    {
        cscf_gen_impl(x)
    }
    #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
    {
        use std::sync::OnceLock;
        static EXECUTOR: OnceLock<unsafe fn(f32) -> f32> = OnceLock::new();
        let q = EXECUTOR.get_or_init(|| {
            if std::arch::is_x86_feature_detected!("avx")
                && std::arch::is_x86_feature_detected!("fma")
            {
                cscf_fma_impl
            } else {
                cscf_gen_impl
            }
        });
        unsafe { q(x) }
    }
}

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

    #[test]
    fn f_cscf_test() {
        assert_eq!(f_cscf(0.04915107), 20.353632);
        assert_eq!(f_cscf(0.5), 2.0858297);
        assert_eq!(f_cscf(0.07), 14.297387);
        assert_eq!(f_cscf(3.6171106e-5), 27646.375);
        assert_eq!(f_cscf(-5.535772e-10), -1806432800.0);
        assert_eq!(f_cscf(0.0), f32::INFINITY);
        assert_eq!(f_cscf(-0.0), f32::NEG_INFINITY);
        assert_eq!(f_cscf(-1.0854926e-19), -9.2124077e18);
    }
}
