"""Thư viện phát tín hiệu âm thanh phản hồi (Audio Feedback) an toàn luồng cho AutoPOE2.

Sử dụng hàng đợi bounded Queue kết hợp một luồng nền Daemon duy nhất để xử lý
tất cả các yêu cầu phát tiếng Bíp. Triệt tiêu hoàn toàn tình trạng rò rỉ luồng vô thừa nhận
(unmanaged thread leak) do việc liên tục gọi threading.Thread().start() gây ra.
Tuân thủ nghiêm ngặt chuẩn tài liệu Google Docstrings theo Rule 16.
"""

import os
import queue
import threading
from typing import List, Tuple

try:
    import winsound
    _HAS_WINSOUND = True
except ImportError:
    winsound = None  # type: ignore
    _HAS_WINSOUND = False


class _AudioDispatcher:
    """Bộ điều phối âm thanh nền Singleton, thread-safe và không rò rỉ tài nguyên luồng."""

    def __init__(self, max_queue_size: int = 16):
        self._queue: queue.Queue[List[Tuple[int, int]]] = queue.Queue(maxsize=max_queue_size)
        self._thread: threading.Thread = threading.Thread(
            target=self._worker_loop, daemon=True, name="AutoPOE2_AudioFeedbackWorker"
        )
        self._started = False
        self._lock = threading.Lock()

    def _ensure_started(self) -> None:
        if not self._started:
            with self._lock:
                if not self._started:
                    self._thread.start()
                    self._started = True

    def enqueue_beeps(self, beeps: List[Tuple[int, int]]) -> None:
        """Đưa danh sách nốt bíp [(tần số Hz, thời lượng ms)] vào hàng đợi phát âm thanh."""
        if not _HAS_WINSOUND or os.name != "nt":
            return
        self._ensure_started()
        try:
            self._queue.put_nowait(beeps)
        except queue.Full:
            # Nếu hàng đợi đầy, bỏ qua để chống trễ âm thanh tích lũy
            pass

    def _worker_loop(self) -> None:
        while True:
            try:
                beeps = self._queue.get()
                for freq, duration in beeps:
                    try:
                        if winsound is not None:
                            winsound.Beep(freq, duration)
                    except Exception:
                        pass
                self._queue.task_done()
            except Exception:
                pass


_dispatcher = _AudioDispatcher()


def enqueue_beep(freq: int, duration: int) -> None:
    """Đưa một nốt bíp đơn lẻ vào hàng đợi phát âm thanh nền (Non-blocking).

    Args:
        freq: Tần số âm thanh (Hz), ví dụ: 600, 1200, 1800.
        duration: Thời lượng phát âm thanh (ms), ví dụ: 100.
    """
    _dispatcher.enqueue_beeps([(freq, duration)])


def enqueue_beeps(beeps: List[Tuple[int, int]]) -> None:
    """Đưa danh sách nốt bíp [(tần số Hz, thời lượng ms)] vào hàng đợi phát âm thanh nền."""
    _dispatcher.enqueue_beeps(beeps)



def beep_bot_toggle(enabled: bool) -> None:
    """Phát tín hiệu âm thanh thông báo trạng thái Bật/Tắt của Bot (Non-blocking).

    Phát âm thanh tần số cao báo hiệu kích hoạt và âm trầm báo hiệu vô hiệu hóa.

    Args:
        enabled: True nếu bot vừa được bật, False nếu vừa được tắt.

    Thread-safety:
        Thread-safe. Non-blocking, đẩy tác vụ vào hàng đợi nền.

    Example:
        >>> beep_bot_toggle(True)   # Âm báo bật (1200Hz)
        >>> beep_bot_toggle(False)  # Âm báo tắt (600Hz)
    """
    if enabled:
        _dispatcher.enqueue_beeps([(1200, 100)])
    else:
        _dispatcher.enqueue_beeps([(600, 120)])


def beep_panic() -> None:
    """Phát chuỗi âm thanh báo động khẩn cấp khi gặp sự cố nghiêm trọng (Panic Alarm).

    Phát 2 nốt cao liên tiếp (1800Hz) để cảnh báo tức thì người dùng khi có sự cố
    như ngắt kết nối game đột ngột, vi phạm bất biến hoặc kích hoạt Emergency Logout.

    Thread-safety:
        Thread-safe. Non-blocking.

    Example:
        >>> beep_panic()
    """
    _dispatcher.enqueue_beeps([(1800, 120), (1800, 150)])


def beep_notification() -> None:
    """Phát âm thanh thông báo nhẹ khi hoàn thành một tác vụ thông thường.

    Phù hợp cho các sự kiện như nhặt được đồ giá trị cao, hoàn thành map,
    hoặc hoàn tất chu trình định danh vật phẩm.

    Thread-safety:
        Thread-safe. Non-blocking.

    Example:
        >>> beep_notification()
    """
    _dispatcher.enqueue_beeps([(900, 80)])
