import SwiftUI
import FoundationModels
import Observation

@Observable class ApplicationData {
   var response: AttributedString = ""
   var prompt: String = ""
   var modelAvailable: Bool = false
   @ObservationIgnored var model: SystemLanguageModel
   @ObservationIgnored var session: LanguageModelSession

   static let shared: ApplicationData = ApplicationData()
   private init() {
      model = SystemLanguageModel.default
      session = LanguageModelSession(model: model)
   }
   func checkAvailability() {
      switch model.availability {
         case .available:
            modelAvailable = true
         case .unavailable(.appleIntelligenceNotEnabled):
            modelAvailable = false
            response = AttributedString("Enable Apple Intelligence from Settings")
         case .unavailable(.deviceNotEligible):
            modelAvailable = false
            response = AttributedString("Apple Intelligence is not available")
         case .unavailable(.modelNotReady):
            modelAvailable = false
            response = AttributedString("The model is not ready yet")
         case .unavailable(let reason):
            modelAvailable = false
            response = AttributedString("Unavailable: \(reason)")
      }
   }
   func sendPrompt() async {
      do {
         let answer = try await session.respond(to: prompt)

         var newResponse = AttributedString("\(answer.content)\n\n")
         newResponse.font = .system(size: 16, weight: .regular)
         response.append(newResponse)
      } catch {
         response.append(AttributedString("Error accessing the model: \(error)\n\n"))
      }
      prompt = ""
   }
}