/*
 * Copyright (C) 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/>.
 */

#pragma once

#include <kylin-ai/ai-engine/embeddingengine.h>

#include <condition_variable>
#include <map>
#include <mutex>
#include <queue>
#include <thread>

#include "embeddingproxy.h"

namespace ai_engine::core_ai::embedding {
class EmbeddingTask;

class EmbeddingServer {
public:
    EmbeddingServer();
    ~EmbeddingServer();

    std::string modelInfo() const;

    void setEmbeddingResultCallback(EmbeddingResultCallback callback);

    result::AiEngineBaseResult initTextEmbeddingModule();
    result::AiEngineBaseResult destroyTextEmbeddingModule();
    result::AiEngineBaseResult embeddingText(const std::string &text);

    result::AiEngineBaseResult initImageEmbeddingModule();
    result::AiEngineBaseResult destroyImageEmbeddingModule();
    result::AiEngineBaseResult embeddingImageFromImageFile(
        const std::string &filePath);
    result::AiEngineBaseResult embeddingImageFromBase64ImageData(
        const std::string &fileData);
    result::AiEngineBaseResult embeddingTextWithImageModel(
        const std::string &text);

private:
    bool addTask(const EmbeddingTask &task);
    void processTaskInThread();
    EmbeddingProxyResult doEmbeddingInThread(const EmbeddingTask &task);
    bool createTritonClient();

private:
    std::unique_ptr<EmbeddingProxy> embeddingProxy_;
    bool startServer_ = false;

    std::thread processTaskThread_;
    std::mutex mutex_;
    std::mutex taskMutex_;
    std::condition_variable taskQueueCv_;

    std::priority_queue<EmbeddingTask> tasks_;
    std::map<std::string, EmbeddingResultCallback> callbacks_;
    EmbeddingResultCallback callback_ = nullptr;
};
}  // namespace ai_engine::core_ai::embedding
