use std::path::PathBuf;
use std::process::{Command, Stdio};

use tracing::warn;

fn sound_path() -> Option<PathBuf> {
    [
        "/usr/share/sounds/forge-camera.ogg",
        "res/sounds/camera.ogg",
        "/usr/share/sounds/freedesktop/stereo/camera-shutter.oga",
    ]
    .into_iter()
    .map(PathBuf::from)
    .find(|p| p.exists())
}

/// Play the camera shutter sound on a detached thread so it never blocks the
/// render loop and the player process is reaped. `paplay` (PulseAudio, the same
/// interface forge already drives via `pactl`) is preferred for reliability;
/// `pw-play` is only tried when `paplay` is not installed — its native PipeWire
/// connection can stall for ~30s on a cold start.
pub fn play_shutter() {
    let Some(path) = sound_path() else {
        warn!("screenshot: no shutter sound found");
        return;
    };
    std::thread::spawn(move || {
        for player in ["paplay", "pw-play"] {
            match Command::new(player)
                .arg(&path)
                .stdin(Stdio::null())
                .stdout(Stdio::null())
                .stderr(Stdio::null())
                .status()
            {
                // The player ran: done either way — don't fall through to the
                // next one (a redundant play, or a slow second connection).
                Ok(status) => {
                    if !status.success() {
                        warn!("screenshot: {player} exited with {status}");
                    }
                    return;
                }
                // Binary missing: try the next player.
                Err(_) => continue,
            }
        }
        warn!("screenshot: no audio player available to play {}", path.display());
    });
}
