use std::slice::from_raw_parts_mut;

/// A 128-bit Xorshift random number generator.
///
/// # Examples
///
/// ```
/// use rng_pack::xorshift128::Xorshift128;
///
/// let mut rng = Xorshift128::new([1, 2, 3, 4]);
/// let val = rng.nexti();
/// ```
#[repr(C)]
pub struct Xorshift128 {
    x: [u32; 4],
}

impl Xorshift128 {
    /// Creates a new `Xorshift128` instance.
    ///
    /// # Arguments
    ///
    /// * `seed` - The initial seed as an array of four `u32` values.
    pub fn new(seed: [u32; 4]) -> Self {
        Self { x: seed }
    }

    /// Generates the next random `u32` value.
    ///
    /// # Examples
    ///
    /// ```
    /// use rng_pack::xorshift128::Xorshift128;
    ///
    /// let mut rng = Xorshift128::new([1, 2, 3, 4]);
    /// let val = rng.nexti();
    /// ```
    #[inline]
    pub fn nexti(&mut self) -> u32 {
        let mut t = self.x[3];
        t ^= t << 11;
        t ^= t >> 8;

        let s = self.x[0];
        (self.x[1], self.x[2], self.x[3]) = (s, self.x[1], self.x[2]);

        self.x[0] = t ^ s ^ (s >> 19);
        self.x[0]
    }

    /// Generates the next random `f32` value in the range [0, 1).
    ///
    /// # Examples
    ///
    /// ```
    /// use rng_pack::xorshift128::Xorshift128;
    ///
    /// let mut rng = Xorshift128::new([1, 2, 3, 4]);
    /// let val = rng.nextf();
    /// assert!(val >= 0.0 && val < 1.0);
    /// ```
    #[inline]
    pub fn nextf(&mut self) -> f32 {
        self.nexti() as f32 * (1.0 / u32::MAX as f32)
    }

    /// Generates a random `i32` value in the range [min, max].
    ///
    /// # Arguments
    ///
    /// * `min` - The lower bound (inclusive).
    /// * `max` - The upper bound (inclusive).
    ///
    /// # Examples
    ///
    /// ```
    /// use rng_pack::xorshift128::Xorshift128;
    ///
    /// let mut rng = Xorshift128::new([1, 2, 3, 4]);
    /// let val = rng.randi(1, 10);
    /// assert!(val >= 1 && val <= 10);
    /// ```
    #[inline]
    pub fn randi(&mut self, min: i32, max: i32) -> i32 {
        let range = (max as i64 - min as i64 + 1) as u64;
        let x = self.nexti();
        ((x as u64 * range) >> 32) as i32 + min
    }

    /// Generates a random `f32` value in the range [min, max).
    ///
    /// # Arguments
    ///
    /// * `min` - The lower bound (inclusive).
    /// * `max` - The upper bound (exclusive).
    ///
    /// # Examples
    ///
    /// ```
    /// use rng_pack::xorshift128::Xorshift128;
    ///
    /// let mut rng = Xorshift128::new([1, 2, 3, 4]);
    /// let val = rng.randf(1.0, 10.0);
    /// assert!(val >= 1.0 && val < 10.0);
    /// ```
    #[inline]
    pub fn randf(&mut self, min: f32, max: f32) -> f32 {
        let range = max - min;
        let scale = range * (1.0 / u32::MAX as f32);
        (self.nexti() as f32 * scale) + min
    }
}

#[unsafe(no_mangle)]
pub extern "C" fn xorshift128_new(
    seed1: u32,
    seed2: u32,
    seed3: u32,
    seed4: u32,
) -> *mut Xorshift128 {
    Box::into_raw(Box::new(Xorshift128::new([seed1, seed2, seed3, seed4])))
}

#[unsafe(no_mangle)]
pub extern "C" fn xorshift128_free(ptr: *mut Xorshift128) {
    if !ptr.is_null() {
        unsafe { drop(Box::from_raw(ptr)) };
    }
}

#[unsafe(no_mangle)]
pub extern "C" fn xorshift128_next_u32s(ptr: *mut Xorshift128, out: *mut u32, count: usize) {
    unsafe {
        let rng = &mut *ptr;
        let buffer = from_raw_parts_mut(out, count);
        for v in buffer.chunks_mut(1) {
            v[0] = rng.nexti();
        }
    }
}

#[unsafe(no_mangle)]
pub extern "C" fn xorshift128_next_f32s(ptr: *mut Xorshift128, out: *mut f32, count: usize) {
    unsafe {
        let rng = &mut *ptr;
        let buffer = from_raw_parts_mut(out, count);
        let scale = 1.0 / (u32::MAX as f32 + 1.0);
        for v in buffer.chunks_mut(1) {
            v[0] = rng.nexti() as f32 * scale;
        }
    }
}

#[unsafe(no_mangle)]
pub extern "C" fn xorshift128_rand_i32s(
    ptr: *mut Xorshift128,
    out: *mut i32,
    count: usize,
    min: i32,
    max: i32,
) {
    unsafe {
        let rng = &mut *ptr;
        let buffer = from_raw_parts_mut(out, count);
        let range = (max - min + 1) as u64;
        for v in buffer.chunks_mut(1) {
            v[0] = (rng.nexti() as u64 % range) as i32 + min;
        }
    }
}

#[unsafe(no_mangle)]
pub extern "C" fn xorshift128_rand_f32s(
    ptr: *mut Xorshift128,
    out: *mut f32,
    count: usize,
    min: f32,
    max: f32,
) {
    unsafe {
        let rng = &mut *ptr;
        let buffer = from_raw_parts_mut(out, count);
        let range = max - min;
        let scale = 1.0 / (u32::MAX as f32);
        for v in buffer.chunks_mut(1) {
            v[0] = (rng.nexti() as f32 * scale) * range + min;
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::xorshift128::Xorshift128;

    #[test]
    fn test_xorshift128() {
        let rng = &mut Xorshift128::new([1, 2, 3, 4]);
        assert_eq!(rng.nexti(), 8229);
    }

    #[test]
    fn test_xorshift128_methods() {
        let mut rng = Xorshift128::new([1, 2, 3, 4]);
        let _ = rng.nexti();
        let f = rng.nextf();
        assert!(f >= 0.0 && f < 1.0);
        let i = rng.randi(10, 20);
        assert!(i >= 10 && i <= 20);
        let rf = rng.randf(10.0, 20.0);
        assert!(rf >= 10.0 && rf < 20.0);
    }
}
