import SwiftUI
import Speech

@Observable class TranscriberData {
   var partialText = AttributedString("")
   var finalText = AttributedString("")
   var recordingTask: Task<(), Never>?

   static let shared: TranscriberData = TranscriberData()
   private init() { }

   func startRecording() async {
      finalText = AttributedString("")
      partialText = AttributedString("")

      // Ask authorization to access Microphone
      if AVCaptureDevice.authorizationStatus(for: .audio) != .authorized {
         guard await AVCaptureDevice.requestAccess(for: .audio) else { return }
      }
      recordingTask = Task {
         do {
            // Set up transcriber and analyzer
            let locale = Locale.current
            let transcriber = DictationTranscriber(locale: locale, preset: .progressiveShortDictation)
            let analyzer = SpeechAnalyzer(modules: [transcriber])

            // Read the results while the audio is analyzed
            let resultsTask = Task {
               for try await response in transcriber.results {
                  if response.isFinal {
                     finalText += response.text
                     partialText = ""
                  } else {
                     partialText = response.text
                     partialText.foregroundColor = .blue.opacity(0.6)
                  }
               }
            }
            // Capture and analyze the audio in the background
            try await analyzeAudio(transcriber: transcriber, analyzer: analyzer)
            try await resultsTask.value
         } catch {
            finalText = AttributedString("Error \(error)")
         }
      }
   }
   @concurrent nonisolated func analyzeAudio(transcriber: DictationTranscriber, analyzer: SpeechAnalyzer) async throws {
      guard let device = AVCaptureDevice.default(.microphone, for: .audio, position: .unspecified) else {
         await analyzer.cancelAndFinishNow()
         return
      }
      let provider = try await CaptureInputSequenceProvider.providerWithSession(from: device, compatibleWith: [transcriber])
      let captureSession = provider.captureSession

      captureSession.startRunning()
      if let lastAudioTime = try await analyzer.analyzeSequence(provider.analyzerInputs) {
         try await analyzer.finalizeAndFinish(through: lastAudioTime)
      } else {
         await analyzer.cancelAndFinishNow()
      }
      captureSession.stopRunning()
   }
   func stopRecording() async {
      recordingTask?.cancel()
      recordingTask = nil
   }
}