import AVFoundation

@Observable
@MainActor
final class SpeechService {
    private let synthesizer = AVSpeechSynthesizer()
    private let spanishVoice: AVSpeechSynthesisVoice?
    private var audioSessionConfigured = false

    init() {
        spanishVoice = AVSpeechSynthesisVoice(language: "es-ES")
    }

    func speak(_ text: String) {
        configureAudioSession()
        synthesizer.stopSpeaking(at: .immediate)
        let utterance = AVSpeechUtterance(string: text)
        utterance.voice = spanishVoice
        utterance.rate = 0.45
        utterance.pitchMultiplier = 1.0
        utterance.preUtteranceDelay = 0
        utterance.postUtteranceDelay = 0
        synthesizer.speak(utterance)
    }

    func stop() {
        synthesizer.stopSpeaking(at: .immediate)
    }

    private func configureAudioSession() {
        guard !audioSessionConfigured else { return }
        do {
            let session = AVAudioSession.sharedInstance()
            try session.setCategory(.playback, mode: .default, options: [.duckOthers])
            try session.setActive(true)
            audioSessionConfigured = true
        } catch {
            print("Failed to configure audio session: \(error)")
        }
    }
}
