import SwiftUI
import Speech

@Observable class ApplicationData {
   var message: String = "Loading..."
   var isAvailable: Bool = false

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

   func checkAvailability() async {
      let locale = Locale.current
      let transcriber = SpeechTranscriber(locale: locale, preset: .transcription)

      // Check if speech is available
      guard SpeechTranscriber.isAvailable else {
         message = "Speech transcriber is not available"
         return
      }
      // Check if the language is supported
      let listSupported = await SpeechTranscriber.supportedLocales
      guard listSupported.map({ $0.identifier(.bcp47) }).contains(locale.identifier(.bcp47)) else {
         message = "Language not supported"
         return
      }
      // Check if language is installed
      let listInstalled = await SpeechTranscriber.installedLocales
      if listInstalled.map({ $0.identifier(.bcp47) }).contains(locale.identifier(.bcp47)) {
         message = "Ready to use!"
         isAvailable = true
      } else {
         do {
            // Download model
            if let downloader = try await AssetInventory.assetInstallationRequest(supporting: [transcriber]) {
               try await downloader.downloadAndInstall()
            }
            message = "Ready to use!"
            isAvailable = true
         } catch {
            message = "Error downloading resources"
         }
      }
   }
}