"""
🎵 Audio module for the Blue Lobster jumpscare.

If the music is too loud, you're too productive.
"""

import os
import logging
from pathlib import Path
from typing import Optional

logger = logging.getLogger(__name__)

# Global mixer state
_mixer_initialized = False


def _get_audio_path() -> Path:
    """Get the path to the jumpscare audio file."""
    # Check multiple locations
    locations = [
        # Installed package assets
        Path(__file__).parent.parent.parent / "assets" / "jumpscare.mp3",
        # Development assets
        Path(__file__).parent.parent.parent.parent / "assets" / "jumpscare.mp3",
        # Current directory
        Path.cwd() / "assets" / "jumpscare.mp3",
        Path.cwd() / "jumpscare.mp3",
        # User's home directory
        Path.home() / ".bluelobster" / "jumpscare.mp3",
    ]
    
    for loc in locations:
        if loc.exists():
            return loc
    
    return locations[0]  # Return default even if not exists


def _init_mixer() -> bool:
    """Initialize pygame mixer. Returns True if successful."""
    global _mixer_initialized
    
    if _mixer_initialized:
        return True
    
    try:
        # Set environment to hide pygame welcome message
        os.environ.setdefault('PYGAME_HIDE_SUPPORT_PROMPT', '1')
        
        import pygame
        pygame.mixer.init(frequency=44100, size=-16, channels=2, buffer=512)
        _mixer_initialized = True
        logger.debug("🎵 Audio mixer initialized")
        return True
    except Exception as e:
        logger.warning(f"Failed to initialize audio mixer: {e}")
        return False


def play_jumpscare(audio_path: Optional[str] = None, blocking: bool = False) -> bool:
    """
    Play the Blue Lobster jumpscare sound (Bach's Toccata and Fugue in D minor).
    
    Args:
        audio_path: Optional custom path to audio file. Defaults to bundled jumpscare.mp3
        blocking: If True, wait for audio to finish. Default False for async playback.
    
    Returns:
        True if audio started playing, False otherwise.
    """
    if not _init_mixer():
        logger.error("🔇 Audio not available - mixer failed to initialize")
        return False
    
    import pygame
    
    path = Path(audio_path) if audio_path else _get_audio_path()
    
    if not path.exists():
        logger.warning(f"🔇 Audio file not found: {path}")
        logger.info("💡 Place your jumpscare.mp3 in ./assets/ or ~/.bluelobster/")
        return False
    
    try:
        pygame.mixer.music.load(str(path))
        pygame.mixer.music.play()
        logger.info("🦞 JUMPSCARE! Bach's Toccata playing...")
        
        if blocking:
            while pygame.mixer.music.get_busy():
                pygame.time.Clock().tick(10)
        
        return True
    except Exception as e:
        logger.error(f"Failed to play audio: {e}")
        return False


def stop_audio() -> None:
    """Stop any currently playing audio."""
    if not _mixer_initialized:
        return
    
    try:
        import pygame
        pygame.mixer.music.stop()
        logger.debug("🔇 Audio stopped")
    except Exception:
        pass


def cleanup() -> None:
    """Cleanup audio resources."""
    global _mixer_initialized
    
    if not _mixer_initialized:
        return
    
    try:
        import pygame
        pygame.mixer.quit()
        _mixer_initialized = False
        logger.debug("🎵 Audio mixer cleaned up")
    except Exception:
        pass
