"""Pytest configuration for musicplayer tests."""

import tempfile
from pathlib import Path

import pytest

from pytola_multimedia.musicplayer.audio_player import AudioPlayer
from pytola_multimedia.musicplayer.musicplayer import Playlist, PlaylistManager
from pytola_multimedia.musicplayer.playlist_persistence import PlaylistPersistenceManager


@pytest.fixture
def audio_player():
    """Create an AudioPlayer instance for testing."""
    player = AudioPlayer()
    yield player
    player.cleanup()


@pytest.fixture
def temp_audio_file():
    """Create a temporary audio file for testing."""
    with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp_file:
        tmp_path = Path(tmp_file.name)

    # Create a minimal valid WAV file header (44 bytes)
    wav_header = (
        b"RIFF"  # RIFF header
        b"\x24\x00\x00\x00"  # File size (36 bytes + 8 for RIFF)
        b"WAVE"  # WAVE header
        b"fmt "  # Format chunk
        b"\x10\x00\x00\x00"  # Format chunk size (16 bytes)
        b"\x01\x00"  # Audio format (PCM = 1)
        b"\x01\x00"  # Number of channels (1 = mono)
        b"\x44\xac\x00\x00"  # Sample rate (44100 Hz)
        b"\x88\x58\x01\x00"  # Byte rate (44100 * 1 * 2)
        b"\x02\x00"  # Block align (1 * 2)
        b"\x10\x00"  # Bits per sample (16)
        b"data"  # Data chunk
        b"\x00\x00\x00\x00"  # Data size (0 bytes)
    )
    tmp_path.write_bytes(wav_header)

    yield tmp_path

    # Cleanup
    if tmp_path.exists():
        tmp_path.unlink()


@pytest.fixture
def temp_playlist_file():
    """Create a temporary playlist file for testing."""
    with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as temp_file:
        temp_path = Path(temp_file.name)

    yield temp_path

    # Cleanup
    if temp_path.exists():
        temp_path.unlink()


@pytest.fixture
def playlist():
    """Create a Playlist instance for testing."""
    return Playlist(name="Test Playlist")


@pytest.fixture
def playlist_manager():
    """Create a PlaylistManager instance with isolated persistence."""
    with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as temp_file:
        temp_path = Path(temp_file.name)

    try:
        persistence_manager = PlaylistPersistenceManager(config_file=temp_path)
        yield PlaylistManager(persistence_manager=persistence_manager)
    finally:
        if temp_path.exists():
            temp_path.unlink()
