"""Lịch sao lưu tự động (không cần thư viện ngoài) + phát hiện thay đổi cấu hình (config drift)."""
from __future__ import annotations

import threading
from typing import Callable, Optional

from .engine import Engine
from .logger import get_logger


class BackupScheduler:
    def __init__(self, engine: Engine, get_devices: Callable[[], list[dict]]):
        self.engine, self.get_devices = engine, get_devices
        self._stop = threading.Event()
        self._thread: Optional[threading.Thread] = None
        self.interval_min = 60
        self.last_stats: Optional[dict] = None
        self.log = get_logger()

    @property
    def running(self) -> bool:
        return bool(self._thread and self._thread.is_alive())

    def start(self, interval_min: int) -> None:
        self.stop()
        self.interval_min = max(1, int(interval_min))
        self._stop.clear()
        self._thread = threading.Thread(target=self._loop, name="backup-scheduler", daemon=True)
        self._thread.start()
        self.log.info("Đã bật sao lưu tự động mỗi %d phút", self.interval_min)

    def stop(self) -> None:
        if self.running:
            self._stop.set()
            self._thread.join(timeout=2)
            self.log.info("Đã tắt sao lưu tự động")

    def _loop(self) -> None:
        while not self._stop.is_set():
            try:
                devs = self.get_devices()
                if devs:
                    self.log.info("Sao lưu tự động: %d thiết bị", len(devs))
                    self.last_stats = self.engine.backup_many(devs, workers=5, note="Sao lưu tự động", cancel=self._stop)
                    self.engine.emit("scheduler", stats=self.last_stats)
            except Exception as e:  # không để luồng chết
                self.log.error("Lỗi sao lưu tự động: %s", e)
            self._stop.wait(self.interval_min * 60)
