"""
Watchdog pour surveillance de l'orchestrateur
"""

import time
import threading
from typing import Callable, Optional
from .utils import get_monotonic_ms, setup_json_logger


class OrchestratorWatchdog:
    """Watchdog pour surveiller l'orchestrateur"""

    def __init__(
        self, timeout_ms: int = 5000, callback: Optional[Callable[[], None]] = None
    ):
        self.timeout_ms = timeout_ms
        self.callback = callback
        self._last_heartbeat_ms = get_monotonic_ms()
        self._is_running = False
        self._thread: Optional[threading.Thread] = None
        self._stop_event = threading.Event()

        self.logger = setup_json_logger("/opt/Skull/logs/motion.log")

    def start(self) -> None:
        """Démarre le watchdog"""
        if self._is_running:
            return

        self._is_running = True
        self._stop_event.clear()
        self._last_heartbeat_ms = get_monotonic_ms()

        self._thread = threading.Thread(target=self._watchdog_loop, daemon=True)
        self._thread.start()

        self.logger.info(f"Watchdog démarré (timeout: {self.timeout_ms}ms)")

    def stop(self) -> None:
        """Arrête le watchdog"""
        if not self._is_running:
            return

        self._is_running = False
        self._stop_event.set()

        if self._thread:
            self._thread.join(timeout=1.0)
            self._thread = None

        self.logger.info("Watchdog arrêté")

    def feed(self) -> None:
        """Nourrit le watchdog (heartbeat)"""
        self._last_heartbeat_ms = get_monotonic_ms()
        self.logger.debug("Watchdog nourri")

    def _watchdog_loop(self) -> None:
        """Boucle principale du watchdog"""
        while self._is_running and not self._stop_event.is_set():
            current_ms = get_monotonic_ms()
            elapsed_ms = current_ms - self._last_heartbeat_ms

            if elapsed_ms > self.timeout_ms:
                self.logger.warning(
                    f"Watchdog timeout! Dernière activité: {elapsed_ms}ms"
                )

                if self.callback:
                    try:
                        self.callback()
                    except Exception as e:
                        self.logger.error(f"Erreur callback watchdog: {e}")

                # Reset pour éviter les déclenchements répétés
                self._last_heartbeat_ms = current_ms

            # Vérification toutes les 500ms
            self._stop_event.wait(0.5)
