/*
 * // 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, is_odd_integerf};
use crate::polyeval::f_polyeval5;
use crate::sin_cosf::sincosf_eval::sincospif_eval;

#[inline(always)]
fn sincospif_gen_impl(x: f32) -> (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.00000009546391
        if x_abs < 0x38a2_f984u32 {
            const PI: f64 = f64::from_bits(0x400921fb54442d18);
            const MPI_E3_OVER_6: f64 = f64::from_bits(0xc014abbce625be53);

            // Small values approximated with Taylor poly for sine
            // x = pi * x - pi^3*x^3/6
            let x2 = xd * xd;
            let p = f_fmla(x2, MPI_E3_OVER_6, PI);
            let sf = (xd * p) as f32;
            #[cfg(any(
                all(
                    any(target_arch = "x86", target_arch = "x86_64"),
                    target_feature = "fma"
                ),
                target_arch = "aarch64"
            ))]
            {
                use crate::common::f_fmlaf;
                let cs = f_fmlaf(x, f32::from_bits(0xb3000000), 1.);
                return (sf, cs);
            }
            #[cfg(not(any(
                all(
                    any(target_arch = "x86", target_arch = "x86_64"),
                    target_feature = "fma"
                ),
                target_arch = "aarch64"
            )))]
            {
                let cs = f_fmla(xd, f64::from_bits(0xbe60000000000000), 1.) as f32;
                return (sf, cs);
            }
        }

        // Cos(x*PI)
        // Generated poly by Sollya:
        // d = [0, 1/16];
        // f_cos = cos(y*pi);
        // Q = fpminimax(f_cos, [|0, 2, 4, 6, 8|], [|D...|], d, relative, floating);
        //
        // See ./notes/cospif.sollya

        let x2 = xd * xd;
        let cs = f_polyeval5(
            x2,
            f64::from_bits(0x3ff0000000000000),
            f64::from_bits(0xc013bd3cc9be43f7),
            f64::from_bits(0x40103c1f08091fe0),
            f64::from_bits(0xbff55d3ba3d94835),
            f64::from_bits(0x3fce173c2a00e74e),
        ) as f32;
        /*
            Sin(x*PI)
            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(
            x2,
            f64::from_bits(0x400921fb54442d18),
            f64::from_bits(0xc014abbce625bbf2),
            f64::from_bits(0x400466bc675e116a),
            f64::from_bits(0xbfe32d2c0b62d41c),
            f64::from_bits(0x3fb501ec4497cb7d),
        );
        let sf = (xd * p) as f32;

        return (sf, cs);
    }

    // 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, x + f32::NAN);
        }
        static SF: [f32; 2] = [0., -0.];
        let sf = SF[x.is_sign_negative() as usize];
        if x_abs < 0x4b80_0000u32 {
            static CF: [f32; 2] = [1., -1.];
            let cs = CF[is_odd_integerf(x) as usize];
            return (sf, cs);
        }
        return (sf, 1.);
    }

    // Formula:
    //   cos(x) = cos((k + y)*pi/32)
    //          = cos(y*pi/32) * cos(k*pi/32) - sin(y*pi/32) * sin(k*pi/32)
    // The values of sin(k*pi/32) and cos(k*pi/32) for k = 0..63 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.
    // Combine the results with the sine of sum formula:
    //   cos(x) = cos((k + y)*pi/32)
    //          = cos(y*pi/32) * cos(k*pi/32) - sin(y*pi/32) * sin(k*pi/32)
    //          = cosm1_y * cos_k + sin_y * sin_k
    //          = (cosm1_y * cos_k + cos_k) + sin_y * sin_k

    //   sin(x) = sin((k + y)*pi/32)
    //          = sin(y*pi/32) * cos(k*pi/32) + cos(y*pi/32) * sin(k*pi/32)

    let rs = sincospif_eval(xd);
    let cs = f_fmla(rs.sin_y, -rs.sin_k, f_fmla(rs.cosm1_y, rs.cos_k, rs.cos_k)) as f32;
    let sf = f_fmla(rs.sin_y, rs.cos_k, f_fmla(rs.cosm1_y, rs.sin_k, rs.sin_k)) as f32;
    (sf, cs)
}

#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
#[target_feature(enable = "avx", enable = "fma")]
unsafe fn sincospif_fma_impl(x: f32) -> (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.00000009546391
        if x_abs < 0x38a2_f984u32 {
            const PI: f64 = f64::from_bits(0x400921fb54442d18);
            const MPI_E3_OVER_6: f64 = f64::from_bits(0xc014abbce625be53);

            // Small values approximated with Taylor poly for sine
            // x = pi * x - pi^3*x^3/6
            let x2 = xd * xd;
            let p = f64::mul_add(x2, MPI_E3_OVER_6, PI);
            let sf = (xd * p) as f32;
            let cs = f32::mul_add(x, f32::from_bits(0xb3000000), 1.);
            return (sf, cs);
        }

        use crate::polyeval::d_polyeval5;

        // Cos(x*PI)
        // Generated poly by Sollya:
        // d = [0, 1/16];
        // f_cos = cos(y*pi);
        // Q = fpminimax(f_cos, [|0, 2, 4, 6, 8|], [|D...|], d, relative, floating);
        //
        // See ./notes/cospif.sollya

        let x2 = xd * xd;
        let cs = d_polyeval5(
            x2,
            f64::from_bits(0x3ff0000000000000),
            f64::from_bits(0xc013bd3cc9be43f7),
            f64::from_bits(0x40103c1f08091fe0),
            f64::from_bits(0xbff55d3ba3d94835),
            f64::from_bits(0x3fce173c2a00e74e),
        ) as f32;
        /*
            Sin(x*PI)
            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 = d_polyeval5(
            x2,
            f64::from_bits(0x400921fb54442d18),
            f64::from_bits(0xc014abbce625bbf2),
            f64::from_bits(0x400466bc675e116a),
            f64::from_bits(0xbfe32d2c0b62d41c),
            f64::from_bits(0x3fb501ec4497cb7d),
        );
        let sf = (xd * p) as f32;

        return (sf, cs);
    }

    // Numbers greater or equal to 2^23 are always integers or NaN
    if x_abs >= 0x4b00_0000u32 || x.round_ties_even() == x {
        if x_abs >= 0x7f80_0000u32 {
            return (x + f32::NAN, x + f32::NAN);
        }
        static SF: [f32; 2] = [0., -0.];
        let sf = SF[x.is_sign_negative() as usize];
        if x_abs < 0x4b80_0000u32 {
            static CF: [f32; 2] = [1., -1.];
            let is_odd_integer = unsafe { (x.to_int_unchecked::<i32>() & 1) != 0 };
            let cs = CF[is_odd_integer as usize];
            return (sf, cs);
        }
        return (sf, 1.);
    }

    // Formula:
    //   cos(x) = cos((k + y)*pi/32)
    //          = cos(y*pi/32) * cos(k*pi/32) - sin(y*pi/32) * sin(k*pi/32)
    // The values of sin(k*pi/32) and cos(k*pi/32) for k = 0..63 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.
    // Combine the results with the sine of sum formula:
    //   cos(x) = cos((k + y)*pi/32)
    //          = cos(y*pi/32) * cos(k*pi/32) - sin(y*pi/32) * sin(k*pi/32)
    //          = cosm1_y * cos_k + sin_y * sin_k
    //          = (cosm1_y * cos_k + cos_k) + sin_y * sin_k

    //   sin(x) = sin((k + y)*pi/32)
    //          = sin(y*pi/32) * cos(k*pi/32) + cos(y*pi/32) * sin(k*pi/32)
    use crate::sin_cosf::sincosf_eval::sincospif_eval_fma;
    let rs = sincospif_eval_fma(xd);
    let cs = f64::mul_add(
        rs.sin_y,
        -rs.sin_k,
        f64::mul_add(rs.cosm1_y, rs.cos_k, rs.cos_k),
    ) as f32;
    let sf = f64::mul_add(
        rs.sin_y,
        rs.cos_k,
        f64::mul_add(rs.cosm1_y, rs.sin_k, rs.sin_k),
    ) as f32;
    (sf, cs)
}

/// Computes sin(x) and cos(x) at the same time
///
/// Max ULP 0.5
#[inline]
pub fn f_sincospif(x: f32) -> (f32, f32) {
    #[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
    {
        sincospif_gen_impl(x)
    }
    #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
    {
        use std::sync::OnceLock;
        static EXECUTOR: OnceLock<unsafe fn(f32) -> (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")
            {
                sincospif_fma_impl
            } else {
                sincospif_gen_impl
            }
        });
        unsafe { q(x) }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{f_cospif, f_sinpif};

    #[test]
    fn test_sincospif() {
        let v0 = f_sincospif(-5.);
        assert_eq!(v0.0, f_sinpif(-5.));
        assert_eq!(v0.1, f_cospif(-5.));

        let v0 = f_sincospif(-4.);
        assert_eq!(v0.0, f_sinpif(-4.));
        assert_eq!(v0.1, f_cospif(-4.));

        let v0 = f_sincospif(4.);
        assert_eq!(v0.0, f_sinpif(4.));
        assert_eq!(v0.1, f_cospif(4.));

        let v0 = f_sincospif(-8489897.0);
        assert_eq!(v0.0, f_sinpif(-8489897.0));
        assert_eq!(v0.1, f_cospif(-8489897.0));

        let v1 = f_sincospif(3.23);
        assert_eq!(v1.0, f_sinpif(3.23));
        assert_eq!(v1.1, f_cospif(3.23));
    }
}
