"""Core batcher implementation for queued log records."""

from __future__ import annotations

import threading
from typing import Callable

from vedatrace.models import LogRecord


class Batcher:
    """Thread-safe in-memory batch buffer."""

    def __init__(
        self,
        batch_size: int,
        on_flush: Callable[[list[LogRecord]], None],
    ) -> None:
        if batch_size <= 0:
            raise ValueError("batch_size must be > 0")
        self._batch_size = batch_size
        self._on_flush = on_flush
        self._lock = threading.Lock()
        self._buffer: list[LogRecord] = []

    def add(self, record: LogRecord) -> bool:
        """Add a record and report whether flush threshold is reached."""

        try:
            with self._lock:
                self._buffer.append(record)
                return len(self._buffer) >= self._batch_size
        except BaseException:
            return False

    def flush(self) -> None:
        """Flush buffered records to callback and clear the buffer."""

        try:
            with self._lock:
                if not self._buffer:
                    return
                records = list(self._buffer)
                self._buffer.clear()
        except BaseException:
            return

        try:
            self._on_flush(records)
        except BaseException:
            return

    def size(self) -> int:
        """Return current buffered record count."""

        with self._lock:
            return len(self._buffer)

    def close(self) -> None:
        """No-op close hook for future lifecycle integration."""

        return None
