import Foundation
import Speech
import AVFoundation

class SpeechRecognizer: ObservableObject {
    private var audioEngine = AVAudioEngine()
    private var request = SFSpeechAudioBufferRecognitionRequest()
    private var recognizer = SFSpeechRecognizer(locale: Locale(identifier: "ja-JP"))
    private var task: SFSpeechRecognitionTask?

    @Published var transcribedText = ""

    func startRecording() {
        SFSpeechRecognizer.requestAuthorization { authStatus in
            guard authStatus == .authorized else { return }

            let node = self.audioEngine.inputNode
            let recordingFormat = node.outputFormat(forBus: 0)
            node.removeTap(onBus: 0)
            node.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { buffer, _ in
                self.request.append(buffer)
            }

            self.audioEngine.prepare()
            try? self.audioEngine.start()

            self.task = self.recognizer?.recognitionTask(with: self.request) { result, error in
                if let result = result {
                    DispatchQueue.main.async {
                        self.transcribedText = result.bestTranscription.formattedString
                    }
                }
            }
        }
    }

    func stopRecording() {
        audioEngine.stop()
        request.endAudio()
        task?.cancel()
        audioEngine.inputNode.removeTap(onBus: 0)
    }
}
