use std::slice::from_raw_parts_mut;

/// A PCG (Permuted Congruential Generator) random number generator.
///
/// This implementation uses the PCG-XSH-RR algorithm with 64-bit state and 32-bit output.
///
/// # Examples
///
/// ```
/// use rng_pack::pcg32::Pcg32;
///
/// let mut rng = Pcg32::new(12345);
/// let val = rng.nextu();
/// ```
#[repr(C)]
pub struct Pcg32 {
    state: u64,
    inc: u64,
}

impl Pcg32 {
    /// Creates a new `Pcg32` instance.
    ///
    /// * `seed` - The initial seed value.
    pub fn new(seed: u64) -> Self {
        Pcg32 {
            state: seed.wrapping_add(0xDA3E39CB94B95BDB),
            inc: seed | 1,
        }
    }

    /// Generates the next random `u32` value.
    ///
    /// # Examples
    ///
    /// ```
    /// use rng_pack::pcg32::Pcg32;
    ///
    /// let mut rng = Pcg32::new(12345);
    /// let val = rng.nextu();
    /// ```
    #[inline]
    pub fn nextu(&mut self) -> u32 {
        let oldstate = self.state;
        self.state = oldstate
            .wrapping_mul(6364136223846793005)
            .wrapping_add(self.inc);

        let xorshifted = (((oldstate >> 18) ^ oldstate) >> 27) as u32;
        let rot = (oldstate >> 59) as u32;
        (xorshifted >> rot) | (xorshifted << (rot.wrapping_neg() & 31))
    }

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

    /// 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::pcg32::Pcg32;
    ///
    /// let mut rng = Pcg32::new(12345);
    /// 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.nextu();
        ((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::pcg32::Pcg32;
    ///
    /// let mut rng = Pcg32::new(12345);
    /// 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 + 1.0));
        (self.nextu() as f32 * scale) + min
    }
}

#[unsafe(no_mangle)]
pub extern "C" fn pcg32_new(seed: u64) -> *mut Pcg32 {
    Box::into_raw(Box::new(Pcg32::new(seed)))
}

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

#[unsafe(no_mangle)]
pub extern "C" fn pcg32_next_u32s(ptr: *mut Pcg32, out: *mut u32, count: usize) {
    unsafe {
        let rng = &mut *ptr;
        let buffer = from_raw_parts_mut(out, count);
        for v in buffer {
            *v = rng.nextu();
        }
    }
}

#[unsafe(no_mangle)]
pub extern "C" fn pcg32_next_f32s(ptr: *mut Pcg32, out: *mut f32, count: usize) {
    unsafe {
        let rng = &mut *ptr;
        let buffer = from_raw_parts_mut(out, count);
        for v in buffer {
            *v = rng.nextf();
        }
    }
}

#[unsafe(no_mangle)]
pub extern "C" fn pcg32_rand_i32s(
    ptr: *mut Pcg32,
    out: *mut i32,
    count: usize,
    min: i32,
    max: i32,
) {
    unsafe {
        let rng = &mut *ptr;
        let buffer = from_raw_parts_mut(out, count);
        for v in buffer {
            *v = rng.randi(min, max);
        }
    }
}

#[unsafe(no_mangle)]
pub extern "C" fn pcg32_rand_f32s(
    ptr: *mut Pcg32,
    out: *mut f32,
    count: usize,
    min: f32,
    max: f32,
) {
    unsafe {
        let rng = &mut *ptr;
        let buffer = from_raw_parts_mut(out, count);
        for v in buffer {
            *v = rng.randf(min, max);
        }
    }
}

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

    #[test]
    fn test_pcg32() {
        let rng = &mut Pcg32::new(1);
        assert_eq!(rng.nextu(), 4164751464);
    }

    #[test]
    fn test_pcg32_methods() {
        let mut rng = Pcg32::new(12345);
        let _ = rng.nextu();
        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);
    }
}
