/*
 * Copyright 2024 KylinSoft Co., Ltd.
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */

#include "genainlpservice.h"

#include <kylin-ai/aiengine.h>
#include <kylin-ai/common/error.h>

#include "chatbot.h"
#include "error.h"
#include "utils/logger.h"
#include "utils/util.h"

namespace {
constexpr const char* interface = "com.kylin.AiRuntime.GenAiNlp";
constexpr const char* objectPath = "/com/kylin/AiRuntime/GenAiNlp";
constexpr const char* chatNlpResultSignal = "ChatNlpResult";
constexpr const char* serviceName = "GenAiNlpService";

GVariant* buildGVariantFromChatResult(const Chatbot::ChatResult& result) {
    GVariantBuilder builder;
    g_variant_builder_init(&builder, G_VARIANT_TYPE_TUPLE);
    g_variant_builder_add(&builder, "s", result.reason_.c_str());
    g_variant_builder_add(&builder, "s", result.finishReason_.c_str());
    g_variant_builder_add(&builder, "i", gen_ai::nlp::error::getNlpErrorCode(result.error_.getCode()));
    g_variant_builder_add(&builder, "s", result.error_.getMessage().c_str());
    g_variant_builder_add(&builder, "b", result.isEnd_);
    g_variant_builder_add(&builder, "s", result.reasoningContent_.c_str());
    GVariant* resultVariant = g_variant_builder_end(&builder);
    return resultVariant;
}
}  // namespace

GenAiNlpService::GenAiNlpService(GDBusConnection& connection, EngineSelector& engineSelector)
    : connection_(connection), engineSelector_(engineSelector) {
    exportSkeleton();
}

GenAiNlpService::~GenAiNlpService() {
    unexportSkeleton();
    LOGD("GenAiNlpService destructor execution completed.");
}

void GenAiNlpService::stop() {
    for (const auto& handlerId : handlerIds_) {
        g_signal_handler_disconnect(delegate_, handlerId);
    }
    handlerIds_.clear();
    for (const auto& [sessionId, chatbot] : chatbots_) {
        chatbot->destroy();
    }
}

void GenAiNlpService::exportSkeleton() {
    delegate_ = ai_runtime_gen_ai_nlp_service_skeleton_new();

    connectSignal();

    GError* error{nullptr};

    isExported_ =
        g_dbus_interface_skeleton_export(G_DBUS_INTERFACE_SKELETON(delegate_), &connection_, objectPath, &error);
    if (!isExported_) {
        LOGE("Error creating server at address {} {}.", objectPath, error->message);
        g_printerr("Error creating server at address %s: %s\n", objectPath, error->message);
        g_error_free(error);
    }
}

void GenAiNlpService::unexportSkeleton() {
    if (delegate_ == nullptr) {
        return;
    }

    if (isExported_) {
        g_dbus_interface_skeleton_unexport_from_connection(G_DBUS_INTERFACE_SKELETON(delegate_), &connection_);
    }
    g_object_unref(delegate_);
}

void GenAiNlpService::connectSignal() {
    gulong handlerId{};
    handlerId = g_signal_connect(delegate_, "handle-init", G_CALLBACK(onHandleInit), this);
    handlerIds_.push_back(handlerId);

    handlerId = g_signal_connect(delegate_, "handle-destroy", G_CALLBACK(onHandleDestroy), this);
    handlerIds_.push_back(handlerId);

    handlerId = g_signal_connect(delegate_, "handle-chat", G_CALLBACK(onHandleChat), this);
    handlerIds_.push_back(handlerId);

    handlerId = g_signal_connect(delegate_, "handle-clear-chat-message", G_CALLBACK(onHandleClearChatMessage), this);
    handlerIds_.push_back(handlerId);

    handlerId = g_signal_connect(delegate_, "handle-stop-chat", G_CALLBACK(onHandleStopChat), this);
    handlerIds_.push_back(handlerId);

    handlerId = g_signal_connect(delegate_, "handle-add-system-message", G_CALLBACK(onHandleAddSystemMessage), this);
    handlerIds_.push_back(handlerId);

    handlerId = g_signal_connect(delegate_, "handle-set-chat-system-prompt-id",
                                 G_CALLBACK(onHandleSetChatSystemPromptId), this);
    handlerIds_.push_back(handlerId);

    handlerId = g_signal_connect(delegate_, "handle-chat-with-history-messages",
                                 G_CALLBACK(onHandleChatWithHistoryMessages), this);
    handlerIds_.push_back(handlerId);
}

int GenAiNlpService::generateRandomSessionId() {
    int sessionId = std::rand();
    while (sessionIdSet_.find(sessionId) != sessionIdSet_.end()) {
        sessionId = std::rand();
    }
    sessionIdSet_.insert(sessionId);
    return sessionId;
}

void GenAiNlpService::releaseRandomSessionId(int sessionId) { sessionIdSet_.erase(sessionId); }

void GenAiNlpService::onChatResult(const Chatbot::ChatResult& chatResult, int sessionId) {
    std::string resultSignalInterfaceName = std::string(interface) + std::to_string(sessionId);
    GVariant* resultVariant = buildGVariantFromChatResult(chatResult);
    g_dbus_connection_emit_signal(&connection_, interface, objectPath, resultSignalInterfaceName.c_str(),
                                  chatNlpResultSignal, resultVariant, nullptr);
}

std::shared_ptr<GenAiNlpService> GenAiNlpService::getSharedObject() { return shared_from_this(); }

bool GenAiNlpService::isSessionIdValid(int sessionId) {
    if (chatbots_.find(sessionId) == chatbots_.end()) {
        return false;
    }
    return true;
}

bool GenAiNlpService::onHandleInit(AiRuntimeGenAiNlpService* service, GDBusMethodInvocation* invocation,
                                   const gchar* config, gpointer userData) {
    auto* nlpService = static_cast<GenAiNlpService*>(userData);
    if (nlpService == nullptr) {
        ai_runtime_gen_ai_nlp_service_complete_init(service, invocation, -1, AISDK_RUNTIME_ERROR);
        return true;
    }

    std::shared_ptr sharedNlpService = nlpService->getSharedObject();

    const GenNlpModelConfig genNlpModelConfigInfo = sharedNlpService->parseModelConfig(config);

    bool isDefaultConfig{};
    if (genNlpModelConfigInfo.name.empty() && genNlpModelConfigInfo.type == DeployType::Default) {
        isDefaultConfig = true;
    } else {
        isDefaultConfig = false;
    }

    std::unique_ptr uniqueNlpEngine = sharedNlpService->selectGenAiNlpModel(genNlpModelConfigInfo);
    // 设置参数
    std::shared_ptr nlpEngine = std::move(uniqueNlpEngine);

    if (nlpEngine == nullptr) {
        ai_runtime_gen_ai_nlp_service_complete_init(service, invocation, -1, AISDK_MODEL_NOT_FOUND);
        LOGE("No nlp engine found!");
        return true;
    }
    int sessionId = sharedNlpService->generateRandomSessionId();

    auto chatbot = std::make_shared<Chatbot>(sharedNlpService->engineSelector_, isDefaultConfig);

    int errorCode = chatbot->init(nlpEngine);
    if (errorCode != AISDK_NO_ERROR) {
        bool isError = false;
        if (isDefaultConfig) {
            // 系统默认配置
            if (errorCode == AISDK_NET_ERROR) {
                // 网络错误不报，留在chat时报错
            } else {
                isError = true;
            }

        } else {
            // 用户指定配置
            isError = true;
        }
        if (isError) {
            LOGE("On handle init: error code: {}", errorCode);
            sharedNlpService->releaseRandomSessionId(sessionId);
            ai_runtime_gen_ai_nlp_service_complete_init(service, invocation, -1, errorCode);
            return true;
        }
    }

    sharedNlpService->chatbots_[sessionId] = chatbot;
    sharedNlpService->chatbots_[sessionId]->setTopK(genNlpModelConfigInfo.topK);
    if (!nlpEngine->isCloud()) {
        LOGI("Nlp engine name {}.", nlpEngine->engineName());
        sharedNlpService->chatbots_[sessionId]->setDeployType(DeployType::Local);
    }

    ai_runtime_gen_ai_nlp_service_complete_init(service, invocation, sessionId, 0);
    LOGI("Init success, nlp engine name: {}.", nlpEngine->engineName());

    std::string uuid = serviceName + std::to_string(sessionId);
    sharedNlpService->engineSelector_.updateAllDeployTypeCallback(
        AiCapability::Nlp, uuid,
        [sharedNlpService, sessionId] { sharedNlpService->modelChangedMap_[sessionId] = true; });

    return true;
}

bool GenAiNlpService::onHandleDestroy(AiRuntimeGenAiNlpService* service, GDBusMethodInvocation* invocation,
                                      int sessionId, gpointer userData) {
    auto* nlpService = static_cast<GenAiNlpService*>(userData);
    if (nlpService == nullptr) {
        LOGE("Gen ai nlp service is null.");
        ai_runtime_gen_ai_nlp_service_complete_destroy(service, invocation);
        return true;
    }
    std::shared_ptr sharedNlpService = nlpService->getSharedObject();

    if (sharedNlpService->isSessionIdValid(sessionId)) {
        sharedNlpService->chatbots_[sessionId]->destroy();
        sharedNlpService->chatbots_.erase(sessionId);
    }
    ai_runtime_gen_ai_nlp_service_complete_destroy(service, invocation);
    return true;
}

bool GenAiNlpService::onHandleChat(AiRuntimeGenAiNlpService* service, GDBusMethodInvocation* invocation, gint sessionId,
                                   gchar* question, gpointer userData) {
    auto* nlpService = static_cast<GenAiNlpService*>(userData);
    if (nlpService == nullptr) {
        LOGE("Gen ai nlp service is null.");
        ai_runtime_gen_ai_nlp_service_complete_chat(service, invocation);
        return true;
    }
    std::shared_ptr sharedNlpService = nlpService->getSharedObject();
    if (!sharedNlpService->isSessionIdValid(sessionId)) {
        std::string errorMessage = fmt::format("SessionId {} not valid", sessionId);
        // 此时sessionId无效，不能通过信号的方式进行通知
        g_dbus_method_invocation_return_error(invocation, G_IO_ERROR, G_IO_ERROR_FAILED, errorMessage.c_str(),
                                              sessionId);
        return true;
    }

    sharedNlpService->tryToChangeModel(sessionId);
    sharedNlpService->chatbots_[sessionId]->chat(
        question,
        [sharedNlpService, sessionId](const Chatbot::ChatResult& result) {
            sharedNlpService->onChatResult(result, sessionId);
        },
        [service, invocation]() { ai_runtime_gen_ai_nlp_service_complete_chat(service, invocation); });

    return true;
}

bool GenAiNlpService::onHandleClearChatMessage(AiRuntimeGenAiNlpService* service, GDBusMethodInvocation* invocation,
                                               gint sessionId, gpointer userData) {
    auto* nlpService = static_cast<GenAiNlpService*>(userData);
    if (nlpService == nullptr) {
        LOGE("Gen ai nlp service is null.");
        ai_runtime_gen_ai_nlp_service_complete_clear_chat_message(service, invocation);
        return true;
    }
    std::shared_ptr sharedNlpService = nlpService->getSharedObject();
    if (sharedNlpService->isSessionIdValid(sessionId)) {
        sharedNlpService->chatbots_[sessionId]->clearChatContext();
    }
    ai_runtime_gen_ai_nlp_service_complete_clear_chat_message(service, invocation);
    return true;
}

bool GenAiNlpService::onHandleStopChat(AiRuntimeGenAiNlpService* service, GDBusMethodInvocation* invocation,
                                       gint sessionId, gpointer userData) {
    auto* nlpService = static_cast<GenAiNlpService*>(userData);
    if (nlpService == nullptr) {
        LOGE("Gen ai nlp service is null.");
        ai_runtime_gen_ai_nlp_service_complete_stop_chat(service, invocation);
        return true;
    }
    std::shared_ptr sharedNlpService = nlpService->getSharedObject();
    if (sharedNlpService->isSessionIdValid(sessionId)) {
        sharedNlpService->chatbots_[sessionId]->stopChat();
    }
    ai_runtime_gen_ai_nlp_service_complete_stop_chat(service, invocation);
    return true;
}

bool GenAiNlpService::onHandleAddSystemMessage(AiRuntimeGenAiNlpService* service, GDBusMethodInvocation* invocation,
                                               gint sessionId, const gchar* message, gpointer userData) {
    auto* nlpService = static_cast<GenAiNlpService*>(userData);
    if (nlpService == nullptr) {
        LOGE("Gen ai nlp service is null.");
        ai_runtime_gen_ai_nlp_service_complete_add_system_message(service, invocation);
        return true;
    }
    std::shared_ptr sharedNlpService = nlpService->getSharedObject();
    if (sharedNlpService->isSessionIdValid(sessionId)) {
        sharedNlpService->chatbots_[sessionId]->addSystemMessage(message);
    }
    ai_runtime_gen_ai_nlp_service_complete_add_system_message(service, invocation);
    return true;
}

bool GenAiNlpService::onHandleSetChatSystemPromptId(AiRuntimeGenAiNlpService* service,
                                                    GDBusMethodInvocation* invocation, gint sessionId, gint promptId,
                                                    gpointer userData) {
    auto* nlpService = static_cast<GenAiNlpService*>(userData);
    if (nlpService == nullptr) {
        LOGE("Gen ai nlp service is null.");
        ai_runtime_gen_ai_nlp_service_complete_set_chat_system_prompt_id(service, invocation);
        return true;
    }
    std::shared_ptr sharedNlpService = nlpService->getSharedObject();
    if (sharedNlpService->isSessionIdValid(sessionId)) {
        sharedNlpService->chatbots_[sessionId]->addSystemMessageByPromptId(
            promptId, sharedNlpService->chatbots_[sessionId]->getDeployType());
    }
    ai_runtime_gen_ai_nlp_service_complete_set_chat_system_prompt_id(service, invocation);
    return true;
}

bool GenAiNlpService::onHandleChatWithHistoryMessages(AiRuntimeGenAiNlpService* service,
                                                      GDBusMethodInvocation* invocation, gint sessionId,
                                                      const gchar* messages, gpointer userData) {
    auto* nlpService = static_cast<GenAiNlpService*>(userData);
    if (nlpService == nullptr) {
        LOGE("Gen ai nlp service is null.");
        ai_runtime_gen_ai_nlp_service_complete_chat_with_history_messages(service, invocation);
        return true;
    }
    std::shared_ptr sharedNlpService = nlpService->getSharedObject();

    if (sharedNlpService->isSessionIdValid(sessionId)) {
        sharedNlpService->tryToChangeModel(sessionId);
        sharedNlpService->chatbots_[sessionId]->chatWithHistoryMessage(
            messages,
            [sharedNlpService, sessionId](const Chatbot::ChatResult& result) {
                sharedNlpService->onChatResult(result, sessionId);
            },
            [service, invocation]() {
                ai_runtime_gen_ai_nlp_service_complete_chat_with_history_messages(service, invocation);
            });
    }
    return true;
}

GenNlpModelConfig GenAiNlpService::parseModelConfig(const std::string& jsonString) {
    GenNlpModelConfig config{};
    if (jsonString.empty()) {
        return config;
    }

    Json::Value root = util::stringToJson(jsonString);

    if (root.isNull()) {
        return config;
    }
    if (root.isMember("name")) {
        config.name = root["name"].asString();
    }
    if (root.isMember("type")) {
        std::string typeStr = root["type"].asString();
        config.type = parseDeployType(typeStr);
    }
    if (root.isMember("topK")) {
        config.topK = root["topK"].asDouble();
    }
    return config;
}

DeployType GenAiNlpService::parseDeployType(const std::string& typeStr) {
    if (typeStr == "Local") {
        return DeployType::Local;
    }
    if (typeStr == "Custom") {
        return DeployType::Custom;
    }
    if (typeStr == "PublicCloud") {
        return DeployType::PublicCloud;
    }
    return DeployType::Default;  // default
}

const std::unique_ptr<ai_engine::gen_ai::nlp::AbstractTextGenerationEngine> GenAiNlpService::selectGenAiNlpModel(
    const GenNlpModelConfig& config) {
    if (config.name.empty()) {
        if (config.type == DeployType::Default) {
            return engineSelector_.selectGenAiTextGenerationEngine();
        }
        return engineSelector_.selectGenAiTextGenerationEngine(config.type);
    }
    return engineSelector_.selectGenAiTextGenerationEngine(config.name);
}

void GenAiNlpService::tryToChangeModel(int sessionId) {
    if (chatbots_.find(sessionId) == chatbots_.end()) {
        return;
    }

    if (modelChangedMap_.find(sessionId) == modelChangedMap_.end()) {
        return;
    }

    if (!modelChangedMap_[sessionId]) {
        return;
    }

    auto& chatbot = chatbots_[sessionId];

    std::unique_ptr uniqueNlpEngine = engineSelector_.selectGenAiTextGenerationEngine();
    std::shared_ptr nlpEngine = std::move(uniqueNlpEngine);
    if (nlpEngine == nullptr) {
        LOGE("No nlp engine found!");
        return;
    }
    if (!chatbot->init(nlpEngine)) {
        return;
    }
    modelChangedMap_[sessionId] = true;
}
