"""MP3-Wiedergabe über Qt (Hauptthread) – zuverlässiger als WMPlayer aus Threads."""

from __future__ import annotations

from pathlib import Path

_player = None
_output = None


def init(parent) -> None:
    global _player, _output
    if _player is not None:
        return
    try:
        from PyQt6.QtMultimedia import QAudioOutput, QMediaPlayer

        _output = QAudioOutput(parent)
        _output.setVolume(1.0)
        _player = QMediaPlayer(parent)
        _player.setAudioOutput(_output)
    except Exception:
        _player = None
        _output = None


def play_mp3(path: Path, timeout_ms: int = 50_000, *, volume: float = 1.0) -> bool:
    if _player is None or not path.exists():
        return False
    try:
        from PyQt6.QtCore import QEventLoop, QTimer, QUrl
        from PyQt6.QtMultimedia import QMediaPlayer

        if _output is not None:
            _output.setVolume(max(0.0, min(1.0, volume)))

        loop = QEventLoop()
        ok = [False]

        def finish(success: bool) -> None:
            if ok[0]:
                return
            ok[0] = success
            try:
                loop.quit()
            except RuntimeError:
                pass

        def on_status(status) -> None:
            if status == QMediaPlayer.MediaStatus.EndOfMedia:
                finish(True)

        def on_error(_err) -> None:
            finish(False)

        _player.mediaStatusChanged.connect(on_status)
        _player.errorOccurred.connect(on_error)
        _player.setSource(QUrl.fromLocalFile(str(path.resolve())))
        _player.play()
        QTimer.singleShot(timeout_ms, lambda: finish(ok[0]))
        loop.exec()
        try:
            _player.mediaStatusChanged.disconnect(on_status)
            _player.errorOccurred.disconnect(on_error)
        except TypeError:
            pass
        _player.stop()
        return ok[0]
    except Exception:
        return False
