#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include "SPI.h"
#include "Adafruit_GFX.h"
#include "Adafruit_ILI9341.h"

#define TFT_DC 2
#define TFT_CS 15
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC);

const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* openai_api_key = "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";

const char* host = "https://api.openai.com";
const int httpsPort = 443;

void setup() {
  Serial.begin(115200);
  tft.begin();
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
    
  }

  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void loop() {
  HTTPClient http;

  http.begin(String(host) + "/v1/engines/gpt-3.5-turbo-0613/completions");
  http.addHeader("Content-Type", "application/json");
  http.addHeader("Authorization", "Bearer " + String(openai_api_key));

  String request_body = "{\"prompt\":\"Hello, OpenAI!\"}";
  int httpCode = http.POST(request_body);
  tft.println(http.getString());
  if (httpCode == HTTP_CODE_OK) {
    String response = http.getString();
    Serial.println(response);

    // Parse the response JSON
    DynamicJsonDocument doc(1024);
    deserializeJson(doc, response);
    String text = doc["choices"][0]["text"].as<String>();
    Serial.println(text);
  } else {
    Serial.println("HTTP POST failed");
  }

  http.end();

  delay(5000);
}