/// A fixed-capacity ring buffer that holds a sliding window of data items.
///
/// When the buffer is full, pushing a new item overwrites the oldest entry.
/// Items are always presented in chronological order (oldest first).
#[derive(Debug, Clone)]
pub struct DataSeries<T: Clone> {
    buf: Vec<T>,
    capacity: usize,
    head: usize,
    len: usize,
}

impl<T: Clone> DataSeries<T> {
    /// Creates a new empty `DataSeries` with the given capacity.
    ///
    /// # Panics
    ///
    /// Panics if `capacity` is zero.
    pub fn new(capacity: usize) -> Self {
        assert!(capacity > 0, "DataSeries capacity must be > 0");
        Self {
            buf: Vec::with_capacity(capacity),
            capacity,
            head: 0,
            len: 0,
        }
    }

    /// Pushes an item into the ring buffer in O(1) time.
    ///
    /// If the buffer is already at capacity the oldest item is overwritten.
    pub fn push(&mut self, item: T) {
        if self.buf.len() < self.capacity {
            // Buffer not yet full -- just append.
            self.buf.push(item);
            self.len = self.buf.len();
            // head stays at 0 while filling up.
        } else {
            // Buffer full -- overwrite at head position.
            self.buf[self.head] = item;
            self.head = (self.head + 1) % self.capacity;
            // len stays at capacity.
        }
    }

    /// Returns the number of items currently stored.
    pub fn len(&self) -> usize {
        self.len
    }

    /// Returns `true` if the buffer contains no items.
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Returns the maximum capacity of the buffer.
    pub fn capacity(&self) -> usize {
        self.capacity
    }

    /// Returns a reference to the item at `index` where 0 is the oldest item.
    ///
    /// Returns `None` if `index` is out of bounds.
    pub fn get(&self, index: usize) -> Option<&T> {
        if index >= self.len {
            return None;
        }
        if self.len < self.capacity {
            // Buffer hasn't wrapped yet.
            Some(&self.buf[index])
        } else {
            // Buffer is full and has wrapped -- head points to the oldest slot.
            let actual = (self.head + index) % self.capacity;
            Some(&self.buf[actual])
        }
    }

    /// Returns an iterator that yields references from oldest to newest.
    pub fn iter(&self) -> impl Iterator<Item = &T> {
        let len = self.len;
        let cap = self.capacity;
        let head = if self.len < self.capacity { 0 } else { self.head };
        let buf = &self.buf;
        (0..len).map(move |i| {
            let actual = (head + i) % cap;
            &buf[actual]
        })
    }

    /// Returns all items as a `Vec<T>` ordered oldest-first.
    pub fn as_slice(&self) -> Vec<T> {
        self.iter().cloned().collect()
    }

    /// Returns a reference to the newest (most recently pushed) item.
    pub fn last(&self) -> Option<&T> {
        if self.len == 0 {
            return None;
        }
        if self.len < self.capacity {
            Some(&self.buf[self.len - 1])
        } else {
            // head points to the next write position, which is the oldest.
            // newest is one step before head.
            let idx = (self.head + self.capacity - 1) % self.capacity;
            Some(&self.buf[idx])
        }
    }

    /// Removes all items, resetting the buffer to empty.
    pub fn clear(&mut self) {
        self.buf.clear();
        self.head = 0;
        self.len = 0;
    }
}

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

    #[test]
    fn basic_push_and_get() {
        let mut s = DataSeries::new(4);
        s.push(10);
        s.push(20);
        s.push(30);
        assert_eq!(s.len(), 3);
        assert_eq!(s.get(0), Some(&10));
        assert_eq!(s.get(1), Some(&20));
        assert_eq!(s.get(2), Some(&30));
        assert_eq!(s.get(3), None);
    }

    #[test]
    fn wraps_around() {
        let mut s = DataSeries::new(3);
        s.push(1);
        s.push(2);
        s.push(3);
        s.push(4); // overwrites 1
        assert_eq!(s.len(), 3);
        assert_eq!(s.get(0), Some(&2));
        assert_eq!(s.get(1), Some(&3));
        assert_eq!(s.get(2), Some(&4));
    }

    #[test]
    fn iter_order() {
        let mut s = DataSeries::new(3);
        s.push(1);
        s.push(2);
        s.push(3);
        s.push(4);
        let v: Vec<_> = s.iter().copied().collect();
        assert_eq!(v, vec![2, 3, 4]);
    }

    #[test]
    fn as_slice_matches_iter() {
        let mut s = DataSeries::new(3);
        for i in 0..5 {
            s.push(i);
        }
        let from_iter: Vec<_> = s.iter().copied().collect();
        assert_eq!(s.as_slice(), from_iter);
    }

    #[test]
    fn last_returns_newest() {
        let mut s = DataSeries::new(3);
        assert!(s.last().is_none());
        s.push(1);
        assert_eq!(s.last(), Some(&1));
        s.push(2);
        s.push(3);
        s.push(4);
        assert_eq!(s.last(), Some(&4));
    }

    #[test]
    fn clear_resets() {
        let mut s = DataSeries::new(3);
        s.push(1);
        s.push(2);
        s.clear();
        assert!(s.is_empty());
        assert_eq!(s.len(), 0);
        assert!(s.get(0).is_none());
    }

    #[test]
    fn capacity_is_correct() {
        let s: DataSeries<i32> = DataSeries::new(10);
        assert_eq!(s.capacity(), 10);
    }

    #[test]
    #[should_panic]
    fn zero_capacity_panics() {
        let _s: DataSeries<i32> = DataSeries::new(0);
    }
}
