"""
Workers spécialisés pour le daemon
"""
import threading
from ..monitoring.logger import logger

try:
    PSUTIL_AVAILABLE = True
except ImportError:
    PSUTIL_AVAILABLE = False
    logger('warning', "[WORKERS] psutil non disponible - surveillance système limitée")


class BaseWorker:
    """Worker de base avec gestion d'erreurs"""
    def __init__(self, name: str):
        self.name = name
        self._stop_event = threading.Event()
        self._thread = None
        
    def start(self):
        """Démarre le worker"""
        if not self._thread or not self._thread.is_alive():
            self._thread = threading.Thread(
                target=self._safe_run, 
                name=f"Worker-{self.name}",
                daemon=True
            )
            self._thread.start()
            logger('debug', f"[WORKER-{self.name}] Démarré")
        
    def stop(self):
        """Arrête le worker"""
        self._stop_event.set()
        if self._thread and self._thread.is_alive():
            self._thread.join(timeout=5)
        logger('debug', f"[WORKER-{self.name}] Arrêté")
    
    def _safe_run(self):
        """Exécution sécurisée avec gestion d'erreurs"""
        try:
            self.run()
        except Exception as e:
            logger('error', f"[WORKER-{self.name}] Erreur: {e}")
    
    def run(self):
        """À implémenter par les classes filles"""
        while not self._stop_event.wait(1):
            pass