import SwiftUI
import Observation

@Observable 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 content: [[String: String]] = [
         ["role": "system", "content": "You are a friendly AI that likes to chat with the user."],
         ["role": "user", "content": prompt]
      ]
      let jsonbody: [String: Any] = [
         "model": "gpt-5",
         "input": content,
         "store": false,
         "max_output_tokens": 2000
      ]
      guard let jsonData = try? JSONSerialization.data(withJSONObject: jsonbody) else { return }

      // Prepare URL request
      let apikey = "[YOUR-API-KEY]"
      guard let url = URL(string: "https://api.openai.com/v1/responses") else { return }

      var urlRequest = URLRequest(url: url)
      urlRequest.httpMethod = "POST"
      urlRequest.httpBody = jsonData
      urlRequest.addValue("Bearer \(apikey)", forHTTPHeaderField: "Authorization")
      urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")

      // Send request and process response
      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 {
                           var newResponse = AttributedString("\(answer)\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 = ""
   }
}