import threading
import time
from datetime import datetime
from typing import Callable, Optional, List

from Copilot.SituationLayer.Core.Incident import IncidentRef
from Copilot.SituationLayer.Analyzers.machineSituationManager import SituationManager

class SituationWorker:
    """
    Background worker for time-based SituationManager tasks.

    Responsibilities:
    - periodically flush stale incident groups
    - emit generated incidents via callback
    """

    def __init__(
        self,
        situation_manager: SituationManager,
        interval_seconds: float = 1.0,
        on_incidents: Optional[Callable[[List[IncidentRef]], None]] = None,
    ):
        self.situation_manager = situation_manager
        self.interval_seconds = interval_seconds
        self.on_incidents = on_incidents

        self._thread = threading.Thread(target=self._run, daemon=True)
        self._stop_event = threading.Event()

    def start(self):
        if not self._thread.is_alive():
            self._thread = threading.Thread(target=self._run, daemon=True)
            self._thread.start()

    def stop(self):
        self._stop_event.set()
        self._thread.join()

    def _run(self):
        while not self._stop_event.is_set():
            try:
                now = datetime.utcnow()

                incidents = self.situation_manager.flush_stale_groups(now)

                if incidents and self.on_incidents:
                    self.on_incidents(incidents)

            except Exception as e:
                print(f"[SituationWorker ERROR] {e}")

            time.sleep(self.interval_seconds)