// origin: FreeBSD /usr/src/lib/msun/src/s_atan.c */
/*
 * ====================================================
 * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
 *
 * Developed at SunPro, a Sun Microsystems, Inc. business.
 * Permission to use, copy, modify, and distribute this
 * software is freely granted, provided that this notice
 * is preserved.
 * ====================================================
 */
/* atan(x)
 * Method
 *   1. Reduce x to positive by atan(x) = -atan(-x).
 *   2. According to the integer k=4t+0.25 chopped, t=x, the argument
 *      is further reduced to one of the following intervals and the
 *      arctangent of t is evaluated by the corresponding formula:
 *
 *      [0,7/16]      atan(x) = t-t^3*(a1+t^2*(a2+...(a10+t^2*a11)...)
 *      [7/16,11/16]  atan(x) = atan(1/2) + atan( (t-0.5)/(1+t/2) )
 *      [11/16.19/16] atan(x) = atan( 1 ) + atan( (t-1)/(1+t) )
 *      [19/16,39/16] atan(x) = atan(3/2) + atan( (t-1.5)/(1+1.5t) )
 *      [39/16,INF]   atan(x) = atan(INF) + atan( -1/t )
 */

#![allow(clippy::indexing_slicing)]
#![allow(clippy::excessive_precision)]
#![allow(clippy::approx_constant)]
#![allow(clippy::eq_op)]

use crate::Real;

const ATANHI: [Real; 4] = [
    4.63647609000806093515e-01, /* atan(0.5)hi 0x3FDDAC67, 0x0561BB4F */
    7.85398163397448278999e-01, /* atan(1.0)hi 0x3FE921FB, 0x54442D18 */
    9.82793723247329054082e-01, /* atan(1.5)hi 0x3FEF730B, 0xD281F69B */
    1.57079632679489655800e+00, /* atan(inf)hi 0x3FF921FB, 0x54442D18 */
];

const ATANLO: [Real; 4] = [
    2.26987774529616870924e-17, /* atan(0.5)lo 0x3C7A2B7F, 0x222F65E2 */
    3.06161699786838301793e-17, /* atan(1.0)lo 0x3C81A626, 0x33145C07 */
    1.39033110312309984516e-17, /* atan(1.5)lo 0x3C700788, 0x7AF0CBBD */
    6.12323399573676603587e-17, /* atan(inf)lo 0x3C91A626, 0x33145C07 */
];

const AT: [Real; 11] = [
    3.33333333333329318027e-01,  /* 0x3FD55555, 0x5555550D */
    -1.99999999998764832476e-01, /* 0xBFC99999, 0x9998EBC4 */
    1.42857142725034663711e-01,  /* 0x3FC24924, 0x920083FF */
    -1.11111104054623557880e-01, /* 0xBFBC71C6, 0xFE231671 */
    9.09088713343650656196e-02,  /* 0x3FB745CD, 0xC54C206E */
    -7.69187620504482999495e-02, /* 0xBFB3B0F2, 0xAF749A6D */
    6.66107313738753120669e-02,  /* 0x3FB10D66, 0xA0D03D51 */
    -5.83357013379057348645e-02, /* 0xBFADDE2D, 0x52DEFD9A */
    4.97687799461593236017e-02,  /* 0x3FA97B4B, 0x24760DEB */
    -3.65315727442169155270e-02, /* 0xBFA2B444, 0x2C6A6C2F */
    1.62858201153657823623e-02,  /* 0x3F90AD3A, 0xE322DA11 */
];

/// Computes the arctangent of `x` (`atan(x)`).
///
/// Returns the principal value in the range `[-π/2, π/2]` radians.
///
/// ## Special cases
///
/// - `atan(NaN)` returns `NaN`
/// - `atan(±0)` returns `±0` (preserving the sign of zero)
/// - `atan(±∞)` returns `±π/2`
///
/// ## Implementation notes
///
/// This is a `const fn`-compatible port of the FreeBSD `libm` implementation
/// (`s_atan.c`). The algorithm reduces the argument based on the magnitude
/// of `|x|` and evaluates it using either a polynomial approximation or
/// an addition formula with precomputed constants (`ATANHI`/`ATANLO`).
///
/// Modifications for this crate:
/// - Adapted to the generic `Real` type (which is `f64` under the hood)
/// - Made fully `const fn` compatible
/// - Removed `force_eval!` (subnormal underflow side-effect, not relevant in const context)
/// - Replaced the `i!` macro with direct array indexing
/// - Used the `.abs()` method instead of the `fabs` helper
///
/// ## Testing
///
/// This function is tested directly with:
/// - Sanity checks for standard angles (π/6, π/4, π/3 and their negatives)
/// - Special values: zero, ±infinity, NaN
///
/// It is also exercised by the full `atan2` test suite (which calls `atan` internally).
/// All tests pass and produce results matching the original libm implementation.
pub const fn atan(x: Real) -> Real {
    let mut x = x;
    let mut ix = (Real::to_bits(x) >> 32) as u32;
    let sign = ix >> 31;
    ix &= 0x7fff_ffff;

    /* |x| >= 2^66 */
    if ix >= 0x4410_0000 {
        if x.is_nan() {
            return x;
        }
        let z = ATANHI[3] + Real::from_bits(0x0380_0000); // tiny value
        return if sign != 0 { -z } else { z };
    }

    /* id:
     * -1  => |x| < 0.4375  (use polynomial directly)
     *  0  => 7/16  <= |x| < 11/16
     *  1  => 11/16 <= |x| < 19/16
     *  2  => 19/16 <= |x| < 39/16
     *  3  => 39/16 <= |x|
     */
    let id = if ix < 0x3fdc_0000 {
        /* |x| < 0.4375 */
        if ix < 0x3e40_0000 {
            /* |x| < 2^-27 */
            if ix < 0x0010_0000 { /* subnormal — original raised underflow via force_eval */ }
            return x;
        }
        -1
    } else {
        x = x.abs();
        if ix < 0x3ff30000 {
            /* |x| < 1.1875 */
            if ix < 0x3fe60000 {
                /* 7/16 <= |x| < 11/16 */
                x = (Real::from_bits(0x4000000000000000) * x - Real::from_bits(0x3FF0000000000000))
                    / (Real::from_bits(0x4000000000000000) + x);
                0
            } else {
                /* 11/16 <= |x| < 19/16 */
                x = (x - Real::from_bits(0x3FF0000000000000))
                    / (x + Real::from_bits(0x3FF0000000000000));
                1
            }
        } else if ix < 0x40038000 {
            /* |x| < 2.4375 */
            x = (x - Real::from_bits(0x3ff8000000000000))
                / (Real::from_bits(0x3FF0000000000000) + Real::from_bits(0x3ff8000000000000) * x);
            2
        } else {
            /* 2.4375 <= |x| */
            x = -Real::from_bits(0x3FF0000000000000) / x;
            3
        }
    };

    let z = x * x;
    let w = z * z;

    /* break sum from i=0 to 10 of AT[i]*z**(i+1) into odd/even parts */
    let s1 = z * (AT[0] + w * (AT[2] + w * (AT[4] + w * (AT[6] + w * (AT[8] + w * AT[10])))));
    let s2 = w * (AT[1] + w * (AT[3] + w * (AT[5] + w * (AT[7] + w * AT[9]))));

    if id < 0 {
        return x - x * (s1 + s2);
    }

    let z = ATANHI[id as usize] - (x * (s1 + s2) - ATANLO[id as usize] - x);

    if sign != 0 { -z } else { z }
}

#[cfg(all(test, feature = "std"))]
mod atan_tests {
    use core::f64;

    use super::atan;

    #[test]
    fn sanity_check() {
        for (input, answer) in [
            (3.0_f64.sqrt() / 3.0, f64::consts::FRAC_PI_6),
            (1.0, f64::consts::FRAC_PI_4),
            (3.0_f64.sqrt(), f64::consts::FRAC_PI_3),
            (-3.0_f64.sqrt() / 3.0, -f64::consts::FRAC_PI_6),
            (-1.0, -f64::consts::FRAC_PI_4),
            (-3.0_f64.sqrt(), -f64::consts::FRAC_PI_3),
        ]
        .iter()
        {
            assert!(
                (atan(*input) - answer) / answer < 1e-5,
                "\natan({:.4}/16) = {:.4}, actual: {}",
                input * 16.0,
                answer,
                atan(*input)
            );
        }
    }

    #[test]
    fn zero() {
        assert_eq!(atan(0.0), 0.0);
    }

    #[test]
    fn infinity() {
        assert_eq!(atan(f64::INFINITY), f64::consts::FRAC_PI_2);
    }

    #[test]
    fn minus_infinity() {
        assert_eq!(atan(f64::NEG_INFINITY), -f64::consts::FRAC_PI_2);
    }

    #[test]
    fn nan() {
        assert!(atan(f64::NAN).is_nan());
    }
}
