import SwiftUI
import FoundationModels
import Observation

@Observable class ApplicationData {
   var response: AttributedString = ""
   var prompt: String = ""

   @ObservationIgnored var session: LanguageModelSession

   static let shared: ApplicationData = ApplicationData()
   private init() {
      let instructions = "Determine the city the user is talking about, and return information about it"
      session = LanguageModelSession(tools: [AttractionsTool()], instructions: instructions)
   }
   func sendPrompt() async {
      do {
         let tempResponse = response

         let finalPrompt = Prompt {
            prompt
            "Use the AttractionsTool to find attractions."
         }
         let answer = try await session.respond(to: finalPrompt, generating: CityResponse.self, options: GenerationOptions(sampling: .greedy))
         let city = answer.content

         var message = ""
         for attraction in city.attractions {
            message += "Attraction: \(attraction.name)\n"
            message += "Location: \(attraction.latitude), \(attraction.longitude)\n"
         }
         var newPartial = AttributedString("\(message)\n")
         newPartial.font = .system(size: 16, weight: .regular)
         var newResponse = tempResponse
         newResponse.append(newPartial)

         response = newResponse
      } catch {
         print("Error accessing the model: \(error)")
      }
      prompt = ""
   }
}