"""Thread-safe ring buffer for robot observations."""
from __future__ import annotations

import threading
from collections import deque
from typing import Generic, TypeVar

T = TypeVar("T")


class RingBuffer(Generic[T]):
    """Fixed-capacity FIFO that discards oldest entries when full."""

    def __init__(self, capacity: int):
        self._buf: deque[T] = deque(maxlen=capacity)
        self._lock = threading.Lock()

    def push(self, item: T) -> None:
        with self._lock:
            self._buf.append(item)

    def get_recent(self, n: int) -> list[T]:
        """Return up to n most-recent items (oldest first)."""
        with self._lock:
            items = list(self._buf)
        return items[-n:] if len(items) >= n else items

    def latest(self) -> T | None:
        with self._lock:
            return self._buf[-1] if self._buf else None

    def __len__(self) -> int:
        with self._lock:
            return len(self._buf)
