"""
Audio control (volume, mute) using Windows API via C# helper
"""

import subprocess
import os
from typing import Optional
from pathlib import Path

# Path to the compiled helper
_HELPER_EXE = Path(__file__).parent / "helpers" / "WindowsHelper.exe"


def _ensure_helper_built():
    """Ensure the helper executable exists"""
    if not _HELPER_EXE.exists():
        raise FileNotFoundError(
            f"WindowsHelper.exe not found at {_HELPER_EXE}. "
            "Please run build_windows_helper.ps1 to compile it."
        )


def get_volume() -> Optional[int]:
    """
    Get the current system volume level.

    Returns:
        Volume level as integer (0-100), or None if error

    Example:
        >>> volume = get_volume()
        >>> if volume is not None:
        ...     print(f"Current volume: {volume}%")
    """
    _ensure_helper_built()

    try:
        result = subprocess.run(
            [str(_HELPER_EXE), "audio", "get"],
            capture_output=True,
            text=True,
            timeout=5,
            creationflags=subprocess.CREATE_NO_WINDOW if os.name == 'nt' else 0
        )

        if result.returncode == 0:
            return int(result.stdout.strip())

        return None

    except Exception as e:
        print(f"Error getting volume: {e}")
        return None


def set_volume(level: int) -> bool:
    """
    Set the system volume level.

    Args:
        level: Volume level (0-100)

    Returns:
        True if successful, False otherwise

    Examples:
        >>> set_volume(50)  # Set to 50%
        >>> set_volume(100)  # Set to maximum
        >>> set_volume(0)  # Mute
    """
    _ensure_helper_built()

    # Clamp to valid range
    level = max(0, min(100, level))

    try:
        result = subprocess.run(
            [str(_HELPER_EXE), "audio", "set", str(level)],
            capture_output=True,
            text=True,
            timeout=5,
            creationflags=subprocess.CREATE_NO_WINDOW if os.name == 'nt' else 0
        )

        return result.returncode == 0

    except Exception as e:
        print(f"Error setting volume: {e}")
        return False


def mute() -> bool:
    """
    Mute the system audio (set volume to 0).

    Returns:
        True if successful, False otherwise

    Example:
        >>> mute()
        >>> print("Audio muted")
    """
    _ensure_helper_built()

    try:
        result = subprocess.run(
            [str(_HELPER_EXE), "audio", "mute"],
            capture_output=True,
            text=True,
            timeout=5,
            creationflags=subprocess.CREATE_NO_WINDOW if os.name == 'nt' else 0
        )

        return result.returncode == 0

    except Exception as e:
        print(f"Error muting audio: {e}")
        return False


def unmute() -> bool:
    """
    Unmute the system audio (set volume to 50%).

    Returns:
        True if successful, False otherwise

    Example:
        >>> unmute()
        >>> print("Audio unmuted")
    """
    _ensure_helper_built()

    try:
        result = subprocess.run(
            [str(_HELPER_EXE), "audio", "unmute"],
            capture_output=True,
            text=True,
            timeout=5,
            creationflags=subprocess.CREATE_NO_WINDOW if os.name == 'nt' else 0
        )

        return result.returncode == 0

    except Exception as e:
        print(f"Error unmuting audio: {e}")
        return False


def increase_volume(amount: int = 10) -> bool:
    """
    Increase the system volume by the specified amount.

    Args:
        amount: Amount to increase (default: 10)

    Returns:
        True if successful, False otherwise

    Example:
        >>> increase_volume(10)  # Increase by 10%
        >>> increase_volume(5)   # Increase by 5%
    """
    current = get_volume()
    if current is not None:
        new_level = min(100, current + amount)
        return set_volume(new_level)
    return False


def decrease_volume(amount: int = 10) -> bool:
    """
    Decrease the system volume by the specified amount.

    Args:
        amount: Amount to decrease (default: 10)

    Returns:
        True if successful, False otherwise

    Example:
        >>> decrease_volume(10)  # Decrease by 10%
        >>> decrease_volume(5)   # Decrease by 5%
    """
    current = get_volume()
    if current is not None:
        new_level = max(0, current - amount)
        return set_volume(new_level)
    return False


def is_muted() -> bool:
    """
    Check if the system audio is muted (volume is 0).

    Returns:
        True if muted, False otherwise

    Example:
        >>> if is_muted():
        ...     print("Audio is muted")
    """
    volume = get_volume()
    return volume == 0 if volume is not None else False
