"""
Speaker feedback module using espeak-ng.
Currently disabled — will be enabled when amp + speaker are wired up.
"""

import subprocess
import threading
import queue
import time


class Speaker:
    def __init__(self, speed=150, pitch=50, volume=100):
        self.speed = speed
        self.pitch = pitch
        self.volume = volume
        self._queue = queue.Queue()
        self._running = True
        self._cooldowns = {}
        self._thread = threading.Thread(target=self._worker, daemon=True)
        self._thread.start()

    def say(self, text: str, cooldown: float = 3.0):
        now = time.time()
        if text in self._cooldowns:
            if now - self._cooldowns[text] < cooldown:
                return
        self._cooldowns[text] = now
        self._queue.put(text)

    def say_now(self, text: str):
        while not self._queue.empty():
            try:
                self._queue.get_nowait()
            except queue.Empty:
                break
        self._queue.put(text)

    def _worker(self):
        while self._running:
            try:
                text = self._queue.get(timeout=0.5)
                self._speak(text)
            except queue.Empty:
                continue

    def _speak(self, text: str):
        try:
            subprocess.run(
                [
                    "espeak-ng",
                    "-s", str(self.speed),
                    "-p", str(self.pitch),
                    "-a", str(self.volume),
                    text,
                ],
                timeout=10,
                capture_output=True,
            )
        except FileNotFoundError:
            try:
                subprocess.run(
                    ["espeak", "-s", str(self.speed), text],
                    timeout=10,
                    capture_output=True,
                )
            except FileNotFoundError:
                print(f"[Speaker] No TTS engine found. Would say: {text}")
        except subprocess.TimeoutExpired:
            pass

    def close(self):
        self._running = False
        self._thread.join(timeout=3)


class Alerts:
    READY = "System ready. Following mode active."
    OBSTACLE = "Obstacle ahead."
    OBSTACLE_CLEAR = "Path clear."
    TARGET_LOST = "Target lost. Searching."
    TARGET_FOUND = "Target acquired."
    GESTURE_STOP = "Stopping."
    GESTURE_POINT = "Redirecting to new target."
    GESTURE_RESUME = "Resuming follow."
    GESTURE_RETURN = "Returning to owner."
    SHUTDOWN = "Shutting down. Goodbye."
