use std::slice::from_raw_parts_mut;

/// A 64-bit Xorshift random number generator.
///
/// # Examples
///
/// ```
/// use rng_pack::xorshift64::Xorshift64;
///
/// let mut rng = Xorshift64::new(12345);
/// let val = rng.nextu();
/// ```
#[repr(C)]
pub struct Xorshift64 {
    a: u64,
}

impl Xorshift64 {
    /// Creates a new `Xorshift64` instance.
    ///
    /// # Arguments
    ///
    /// * `seed` - The initial seed value.
    pub fn new(seed: u64) -> Self {
        Self { a: seed }
    }

    /// Generates the next random `u64` value.
    ///
    /// # Examples
    ///
    /// ```
    /// use rng_pack::xorshift64::Xorshift64;
    ///
    /// let mut rng = Xorshift64::new(12345);
    /// let val = rng.nextu();
    /// ```
    #[inline]
    pub fn nextu(&mut self) -> u64 {
        let mut x = self.a;
        x ^= x << 13;
        x ^= x >> 7;
        x ^= x << 17;
        self.a = x;
        x
    }

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

    /// Generates a random `i64` value in the range [min, max].
    ///
    /// # Arguments
    ///
    /// * `min` - The lower bound (inclusive).
    /// * `max` - The upper bound (inclusive).
    ///
    /// # Examples
    ///
    /// ```
    /// use rng_pack::xorshift64::Xorshift64;
    ///
    /// let mut rng = Xorshift64::new(12345);
    /// let val = rng.randi(1, 10);
    /// assert!(val >= 1 && val <= 10);
    /// ```
    #[inline]
    pub fn randi(&mut self, min: i64, max: i64) -> i64 {
        let range = (max as i128 - min as i128 + 1) as u128;
        let x = self.nextu();
        ((x as u128 * range) >> 64) as i64 + min
    }

    /// Generates a random `f64` value in the range [min, max).
    ///
    /// # Arguments
    ///
    /// * `min` - The lower bound (inclusive).
    /// * `max` - The upper bound (exclusive).
    ///
    /// # Examples
    ///
    /// ```
    /// use rng_pack::xorshift64::Xorshift64;
    ///
    /// let mut rng = Xorshift64::new(12345);
    /// let val = rng.randf(1.0, 10.0);
    /// assert!(val >= 1.0 && val < 10.0);
    /// ```
    #[inline]
    pub fn randf(&mut self, min: f64, max: f64) -> f64 {
        let range = max - min;
        let scale = range * (1.0 / (u64::MAX as f64 + 1.0));
        (self.nextu() as f64 * scale) + min
    }
}

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

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

#[unsafe(no_mangle)]
pub extern "C" fn xorshift64_next_u64s(ptr: *mut Xorshift64, out: *mut u64, 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 xorshift64_next_f64s(ptr: *mut Xorshift64, out: *mut f64, 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 xorshift64_rand_i64s(
    ptr: *mut Xorshift64,
    out: *mut i64,
    count: usize,
    min: i64,
    max: i64,
) {
    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 xorshift64_rand_f64s(
    ptr: *mut Xorshift64,
    out: *mut f64,
    count: usize,
    min: f64,
    max: f64,
) {
    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 crate::xorshift64::Xorshift64;

    #[test]
    fn test_xorshift64() {
        let rng = &mut Xorshift64::new(1);
        assert_eq!(rng.nextu(), 1082269761);
    }

    #[test]
    fn test_xorshift64_methods() {
        let mut rng = Xorshift64::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);
    }
}
