import AVFoundation
import os

private let soundLog = Logger(subsystem: "dev.smoll.KDChat", category: "Sound")

enum SoundPlayer {
    private static var players: [String: AVAudioPlayer] = [:]

    static func play(_ name: String) {
        if let cached = players[name] {
            cached.currentTime = 0
            cached.play()
            return
        }
        guard let url = Bundle.main.url(forResource: name, withExtension: "caf") else {
            soundLog.warning("Sound not found: \(name).caf")
            return
        }
        do {
            let player = try AVAudioPlayer(contentsOf: url)
            player.prepareToPlay()
            player.play()
            players[name] = player
        } catch {
            soundLog.error("Failed to play \(name): \(error.localizedDescription)")
        }
    }

    static func configureSession() {
        do {
            try AVAudioSession.sharedInstance().setCategory(.ambient, mode: .default)
        } catch {
            soundLog.error("Failed to configure audio session: \(error.localizedDescription)")
        }
    }
}
