# Copyright 2026 4f4d
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Optional audio playback for f1radio clips."""

from __future__ import annotations

import logging
import os
import threading

from f1radio.exceptions import PlaybackError

logger = logging.getLogger("f1radio")


def play_audio(path: str, block: bool = True) -> None:
    """Play an MP3 file.

    Requires the playback extra: pip install 'f1radio[playback]'
    """
    if not os.path.exists(path):
        raise FileNotFoundError(f"Audio file not found: {path}")

    try:
        from playsound3 import playsound
    except ImportError:
        raise PlaybackError(
            "Audio playback requires the 'playback' extra. "
            "Install it with: pip install 'f1radio[playback]'"
        )

    if block:
        try:
            playsound(path)
        except Exception as e:
            raise PlaybackError(f"Playback failed: {e}")
    else:
        def _play():
            try:
                playsound(path)
            except Exception as e:
                logger.warning(f"Background playback failed: {e}")

        thread = threading.Thread(target=_play, daemon=True)
        thread.start()
