/*
 * Copyright 2025 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/>.
 */

#ifndef DEEPSEEKNLPENGINE_P_H
#define DEEPSEEKNLPENGINE_P_H

#include <jsoncpp/json/json.h>
#include <kylin-ai/ai-engine/aiengineerror.h>
#include <kylin-ai/ai-engine/textgenerationengine.h>

#include "third-party/cpr/include/cpr/cpr.h"

class DeepseekNlpEnginePrivate {
public:
    DeepseekNlpEnginePrivate();
    ~DeepseekNlpEnginePrivate();
    std::string engineName() const;
    std::string currentModel() const;
    std::string currentModelName() const;

    void setConfig(const std::string &config);
    std::string modelInfo() const;

    void setTextGenerationResultCallback(
        ai_engine::gen_ai::nlp::TextGenerationResultCallback callback);

    bool setCurrentModel(const std::string &model);

    ai_engine::result::AiEngineBaseResult generateContent(
        const std::string &input);
    ai_engine::result::AiEngineBaseResult chat(const std::string &message);

    void stopGenerateContent();
    void stopChat();

    ai_engine::result::AiEngineBaseResult init();
    ai_engine::result::AiEngineBaseResult destroy();

private:
    std::string apiKey_;

    ai_engine::gen_ai::nlp::TextGenerationResultCallback
        textGenerationResultCallback_;

    Json::Value context_;
    int sentenceId_{0};
    void clearContext();
    void addContext_(const std::string &role, const std::string &message);
    void removeLastContext_();
    std::vector<Json::Value> streamChatData_;
    std::string tempStreamChatData_;

    friend bool writeChatData(std::string data, intptr_t userData);
    int getMaxTokens(const std::string &model);

    ai_engine::result::AiEngineBaseResult processChatResponse(
        cpr::Response &response);
    void decreaseChatCounter();
    void increaseChatCounter();
    bool isChatRunning() const;

    ai_engine::EngineError currentError_;
    std::string currentErrorInfo_;

    bool waitForStopped();
    std::atomic<bool> isStopped_{false};
    std::atomic<int> chatCounter_{0};

    static std::string systemRole_;
    std::string currentModel_;
    int maxTokens_;
};

#endif  // DEEPSEEKNLPENGINE_P_H
