#include "genainlpserver.h"

namespace kyai::genai::nlp {

const std::string& serverUnixPath = "unix:path=/tmp/.kylin-ai-runtime-unix/" +
                                    std::to_string(getuid()) +
                                    "/genai-nlp.sock";

GenAiNlpServer& GenAiNlpServer::getInstance() {
    static GenAiNlpServer instance{};
    return instance;
}

GenAiNlpServer::~GenAiNlpServer() { destroy(); }

GenAiNlpServer::GenAiNlpServer() { }

void GenAiNlpServer::init() {
    init(serverUnixPath);
}
void GenAiNlpServer::init(const std::string& unixPath) {
    GError* error{nullptr};
    connection_ = g_dbus_connection_new_for_address_sync(
        unixPath.c_str(), G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT,
        nullptr,  // GDBusAuthObserver
        nullptr,  // GCancellable
        &error);
    if (connection_ == nullptr) {
        g_printerr("Error connecting to D-Bus address %s: %s\n",
                   unixPath.c_str(), error->message);
        g_error_free(error);
    }
}

void GenAiNlpServer::destroy() const {
    if (connection_ != nullptr) {
        g_object_unref(connection_);
    }
}

}  // namespace kyai::genai::nlp
