import SwiftUI
import Observation

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

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

   func sendPrompt() async {
      guard !prompt.isEmpty else { return }

      // Prepare JSON instructions
      let jsonbody: [[String: String]] = [["role": "user", "content": prompt]]
      guard let jsonData = try? JSONSerialization.data(withJSONObject: jsonbody) else { return }
      guard let url = URL(string: "https://mynewworker.jdgauchat.workers.dev") else { return }

      // Prepare URL request
      var urlRequest = URLRequest(url: url)
      urlRequest.httpMethod = "POST"
      urlRequest.httpBody = jsonData
      urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")

      do {
         let (data, urlResponse) = try await URLSession.shared.data(for: urlRequest)
         
         if let httpResponse = urlResponse as? HTTPURLResponse {
            if httpResponse.statusCode == 200 {
               let chatresponse = try JSONDecoder().decode(ChatResponse.self, from: data)
               for item in chatresponse.output {
                  if item.type == "message", let content = item.content {
                     for part in content {
                        if part.type == "output_text", let answer = part.text {
                           let message = try parseCity(text: answer)
                           var newResponse = AttributedString("\(message)\n\n")
                           newResponse.font = .system(size: 16, weight: .regular)
                           response.append(newResponse)
                        }
                     }
                  }
               }
            }  else {
               response = AttributedString("Error \(httpResponse.statusCode): \(String(data: data, encoding: .utf8) ?? "No additional information.")")
            }
         }
      } catch {
         response = AttributedString("Error accessing the API: \(error)")
      }
      prompt = ""
   }
   func parseCity(text: String) throws -> String {
      let citydata = Data(text.utf8)
      let cityresponse = try JSONDecoder().decode(CityResponse.self, from: citydata)

      var message = "\(cityresponse.city ?? "Undefined")\n"
      message += "\(cityresponse.country ?? "Undefined")\n"
      message += "\(cityresponse.language ?? "Undefined")\n"
      message += "\(cityresponse.currency ?? "Undefined")\n"
      message += "\(cityresponse.attractions?.joined(separator: ",") ?? "Undefined")\n\n"
      return message
   }
}