/*
 * // 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, is_integerf};
use crate::polyeval::f_polyeval5;
use crate::sin_cosf::argument_reduction_pi::ArgumentReducerPi;
use crate::sin_cosf::sincosf_eval::{cospif_eval, sinpif_eval, sinpif_eval2};

/// Computes sin(PI*x)
///
/// Max ULP 0.5
#[inline]
pub fn f_sinpif(x: f32) -> f32 {
    let x_abs = x.to_bits() & 0x7fff_ffffu32;
    let xd = x as f64;

    // |x| <= 1/16
    if x_abs <= 0x3d80_0000u32 {
        // |x| < 0.0000009546391
        if x_abs < 0x3580_2126u32 {
            if x_abs == 0u32 {
                // For signed zeros.
                return x;
            }
            const PI: f64 = f64::from_bits(0x400921fb54442d18);
            const MPI_E3_OVER_6: f64 = f64::from_bits(0xc014abbce625be53);

            // Small values approximated with Taylor poly
            // x = pi * x - pi^3*x^3/6
            let x2 = xd * xd;
            let p = f_fmla(x2, MPI_E3_OVER_6, PI);
            return (xd * p) as f32;
        }

        let xsqr = xd * xd;

        /*
        Generated by Sollya:
        d = [0, 1/16];
        f_sin = sin(y*pi)/y;
        Q = fpminimax(sin(y*pi)/y, [|0, 2, 4, 6, 8|], [|D...|], d, relative, floating);

        See ./notes/sinpif.sollya
         */
        let p = f_polyeval5(
            xsqr,
            f64::from_bits(0x400921fb54442d18),
            f64::from_bits(0xc014abbce625bbf2),
            f64::from_bits(0x400466bc675e116a),
            f64::from_bits(0xbfe32d2c0b62d41c),
            f64::from_bits(0x3fb501ec4497cb7d),
        );
        return (xd * p) as f32;
    }

    // Numbers greater or equal to 2^23 are always integers or NaN
    if x_abs >= 0x4b00_0000u32 || is_integerf(x) {
        if x_abs >= 0x7f80_0000u32 {
            return x + f32::NAN;
        }
        return if x.is_sign_negative() { -0. } else { 0. };
    }

    // We're computing sin(y) after argument reduction then return valid value
    // based on quadrant

    let reducer = ArgumentReducerPi { x: x as f64 };
    let (y, k) = reducer.reduce_0p25();
    // Decide based on quadrant what kernel function to use
    (match k & 3 {
        0 => sinpif_eval(y),
        1 => cospif_eval(y),
        2 => sinpif_eval(-y),
        _ => -cospif_eval(y),
    }) as f32
}

pub(crate) fn fast_sinpif(x: f32) -> f64 {
    let x_abs = x.to_bits() & 0x7fff_ffffu32;
    let xd = x as f64;

    // |x| <= 1/16
    if x_abs <= 0x3d80_0000u32 {
        // |x| < 0.0000009546391
        if x_abs < 0x3580_2126u32 {
            if x_abs == 0u32 {
                // For signed zeros.
                return x as f64;
            }
            const PI: f64 = f64::from_bits(0x400921fb54442d18);
            const MPI_E3_OVER_6: f64 = f64::from_bits(0xc014abbce625be53);

            // Small values approximated with Taylor poly
            // x = pi * x - pi^3*x^3/6
            let x2 = xd * xd;
            let p = f_fmla(x2, MPI_E3_OVER_6, PI);
            return xd * p;
        }

        let xsqr = xd * xd;

        /*
        Generated by Sollya:
        d = [0, 1/16];
        f_sin = sin(y*pi)/y;
        Q = fpminimax(sin(y*pi)/y, [|0, 2, 4, 6, 8|], [|D...|], d, relative, floating);

        See ./notes/sinpif.sollya
         */
        let p = f_polyeval5(
            xsqr,
            f64::from_bits(0x400921fb54442d18),
            f64::from_bits(0xc014abbce625bbf2),
            f64::from_bits(0x400466bc675e116a),
            f64::from_bits(0xbfe32d2c0b62d41c),
            f64::from_bits(0x3fb501ec4497cb7d),
        );
        return xd * p;
    }

    let reducer = ArgumentReducerPi { x: x as f64 };
    let (y, k) = reducer.reduce_0p25();
    // Decide based on quadrant what kernel function to use
    match k & 3 {
        0 => sinpif_eval2(y),
        1 => cospif_eval(y),
        2 => sinpif_eval2(-y),
        _ => -cospif_eval(y),
    }
}

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

    #[test]
    fn test_f_sinpif() {
        assert_eq!(f_sinpif(3.), 0.);
        assert_eq!(f_sinpif(1.12199515e-7), 3.524852e-7);
        assert_eq!(f_sinpif(-0.31706), -0.83934295);
        assert_eq!(f_sinpif(0.30706), 0.8218538);
        assert_eq!(f_sinpif(115.30706), -0.82185423);
        assert!(f_sinpif(f32::INFINITY).is_nan());
        assert!(f_sinpif(f32::NEG_INFINITY).is_nan());
        assert!(f_sinpif(f32::NAN).is_nan());
    }
}
