import AVFoundation

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

    init() {
        // AVSpeechSynthesisVoice can trigger a malloc double-free on
        // iOS 26 simulators when deserializing voice metadata. Defer
        // voice resolution to first use so the crash doesn't happen
        // during app launch.
        spanishVoice = nil
    }

    func speak(_ text: String) {
        resolveVoiceIfNeeded()
        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 resolveVoiceIfNeeded() {
        guard !voiceResolved else { return }
        voiceResolved = true
        spanishVoice = AVSpeechSynthesisVoice(language: "es-ES")
    }

    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)")
        }
    }
}
