"""Background index maintenance utilities."""
from __future__ import annotations

import logging
import threading
import time
from typing import Callable, Optional


class IndexManager:
    def __init__(
        self,
        rebuild_callback: Callable[[], None],
        *,
        max_records_per_rebuild: int = 10_000,
        rebuild_cooldown_seconds: float = 60.0,
        enabled: bool = False,
    ) -> None:
        self.rebuild_callback = rebuild_callback
        self.max_records_per_rebuild = max_records_per_rebuild
        self.rebuild_cooldown_seconds = rebuild_cooldown_seconds
        self.enabled = enabled
        self._pending = 0
        self._thread: Optional[threading.Thread] = None
        self._stop = threading.Event()
        self._last_rebuild = 0.0

    def start(self) -> None:
        if not self.enabled:
            return
        if self._thread and self._thread.is_alive():
            return
        self._stop.clear()
        self._thread = threading.Thread(target=self._run, daemon=True)
        self._thread.start()

    def stop(self) -> None:
        self._stop.set()
        if self._thread:
            self._thread.join(timeout=1)

    def record_insert(self, count: int = 1) -> None:
        if not self.enabled:
            return
        self._pending += max(1, int(count))

    def _run(self) -> None:
        while not self._stop.is_set():
            now = time.time()
            if (
                self._pending >= self.max_records_per_rebuild
                and now - self._last_rebuild >= self.rebuild_cooldown_seconds
            ):
                self._pending = 0
                self._last_rebuild = now
                try:
                    self.rebuild_callback()
                except Exception as exc:
                    logging.getLogger(__name__).warning(
                        "Index rebuild callback failed: %s", exc
                    )
            time.sleep(1.0)
