"""Audio file validation utilities."""
import os
from pathlib import Path
from typing import List, Optional

SUPPORTED_AUDIO_EXTENSIONS = {".mp3", ".wav", ".flac", ".m4a", ".ogg", ".aac"}


def is_audio_file(filepath: str) -> bool:
    """Check if file is a supported audio format.

    Args:
        filepath: Path to file

    Returns:
        True if file has supported audio extension
    """
    return Path(filepath).suffix.lower() in SUPPORTED_AUDIO_EXTENSIONS


def validate_file_path(filepath: str) -> Optional[str]:
    """Validate and sanitize file path.

    Args:
        filepath: Path to validate

    Returns:
        Sanitized absolute path or None if invalid

    Security:
        - Prevents path traversal attacks
        - Resolves to absolute path
        - Checks file exists
    """
    try:
        # Resolve to absolute path
        abs_path = Path(filepath).resolve()

        # Check file exists
        if not abs_path.exists():
            return None

        # Check it's a file (not directory)
        if not abs_path.is_file():
            return None

        # Check it's an audio file
        if not is_audio_file(str(abs_path)):
            return None

        return str(abs_path)

    except (OSError, ValueError):
        return None


def validate_directory_path(dirpath: str) -> Optional[str]:
    """Validate and sanitize directory path.

    Args:
        dirpath: Directory path to validate

    Returns:
        Sanitized absolute path or None if invalid

    Security:
        - Prevents path traversal attacks
        - Resolves to absolute path
        - Checks directory exists
    """
    try:
        # Resolve to absolute path
        abs_path = Path(dirpath).resolve()

        # Check directory exists
        if not abs_path.exists():
            return None

        # Check it's a directory
        if not abs_path.is_dir():
            return None

        return str(abs_path)

    except (OSError, ValueError):
        return None


def get_audio_files(directory: str, recursive: bool = True) -> List[str]:
    """Get all audio files in directory.

    Args:
        directory: Directory path
        recursive: If True, search recursively

    Returns:
        List of absolute paths to audio files
    """
    audio_files = []
    dir_path = Path(directory)

    if not dir_path.exists() or not dir_path.is_dir():
        return audio_files

    # Choose iterator based on recursive flag
    iterator = dir_path.rglob("*") if recursive else dir_path.glob("*")

    for file_path in iterator:
        if file_path.is_file() and is_audio_file(str(file_path)):
            audio_files.append(str(file_path.resolve()))

    return sorted(audio_files)
