#include "zapi.h"
#include <iostream>

COpenAI::COpenAI()
{
    curl_global_init(CURL_GLOBAL_DEFAULT);
    curl_ = curl_easy_init();
    curl_easy_setopt(curl_, CURLOPT_WRITEFUNCTION, recv_call);
    curl_easy_setopt(curl_, CURLOPT_WRITEDATA, &recv_);
}

COpenAI::~COpenAI()
{
    curl_easy_cleanup(curl_);
    curl_global_cleanup();
}

void COpenAI::set_base(const std::string& api_url, const std::string& key)
{
    api_key_ = key;
    api_url_ = api_url;
    curl_easy_setopt(curl_, CURLOPT_URL, api_url_.c_str());
}

bool COpenAI::post(const std::string& json, std::string& out)
{
    recv_.clear();
    struct curl_slist* headers = nullptr;
    headers = curl_slist_append(headers, ("Authorization: Bearer " + api_key_).c_str());
    headers = curl_slist_append(headers, "Content-Type: application/json");
    curl_easy_setopt(curl_, CURLOPT_HTTPHEADER, headers);
    curl_easy_setopt(curl_, CURLOPT_POSTFIELDS, json.c_str());

    auto res = curl_easy_perform(curl_);
    if (res != CURLE_OK) {
        std::cerr << "curl post failed: " << curl_easy_strerror(res) << std::endl;
    } else {
        //std::cout << recv_ << std::endl;
        out = recv_;
    }
    curl_slist_free_all(headers);
    return res == CURLE_OK;
}

size_t COpenAI::recv_call(void* contents, size_t size, size_t nmemb, std::string* output)
{
    size_t total_size = size * nmemb;
    output->append(reinterpret_cast<char*>(contents), total_size);
    return total_size;
}
