"""
Cross-platform sound player for sweep notifications.

Supports Windows and Linux platforms.
"""

import platform
import threading
from pathlib import Path

from vna_system.core.logging.logger import get_component_logger

logger = get_component_logger(__file__)


class SoundPlayer:
    """Cross-platform sound player using system-specific APIs."""

    def __init__(self, sound_file: Path):
        """
        Initialize sound player with a sound file.

        Args:
            sound_file: Path to the sound file (mp3, wav, etc.)
        """
        self.sound_file = sound_file
        self.system = platform.system()
        self._player = None

        # Validate sound file exists
        if not sound_file.exists():
            logger.warning("Sound file not found", path=str(sound_file))
            return

        # Initialize platform-specific player
        if self.system == "Windows":
            self._init_windows_player()
        elif self.system == "Linux":
            self._init_linux_player()
        else:
            logger.warning("Unsupported platform for sound playback", platform=self.system)

    def _init_windows_player(self):
        """Initialize Windows-specific sound player using winsound."""
        try:
            import winsound
            self._player = lambda: winsound.PlaySound(
                str(self.sound_file),
                winsound.SND_FILENAME | winsound.SND_ASYNC | winsound.SND_NODEFAULT
            )
            logger.debug("Windows sound player initialized")
        except ImportError:
            logger.warning("winsound not available on Windows")
            self._player = None

    def _init_linux_player(self):
        """Initialize Linux-specific sound player using subprocess."""
        import subprocess
        import shutil

        # Try to find available audio players
        players = ["paplay", "aplay", "mpg123", "ffplay"]
        available_player = None

        for player in players:
            if shutil.which(player):
                available_player = player
                break

        if available_player:
            def linux_play():
                try:
                    # Run player silently in background
                    subprocess.Popen(
                        [available_player, str(self.sound_file)],
                        stdout=subprocess.DEVNULL,
                        stderr=subprocess.DEVNULL
                    )
                except Exception as exc:
                    logger.error("Failed to play sound on Linux", error=repr(exc))

            self._player = linux_play
            logger.debug("Linux sound player initialized", player=available_player)
        else:
            logger.warning("No audio player found on Linux", tried=players)
            self._player = None

    def play(self):
        """Play the sound asynchronously (non-blocking)."""
        if self._player is None:
            return

        # Play in a background thread to avoid blocking
        thread = threading.Thread(target=self._player, daemon=True, name="SoundPlayer")
        thread.start()

    def play_sync(self):
        """Play the sound synchronously (blocking)."""
        if self._player is None:
            return
        self._player()
