/*
 * 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 QWENNLPENGINE_P_H
#define QWENNLPENGINE_P_H

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

#include <functional>

#include "cpr/cpr.h"

class QwenNlpEnginePrivate {
public:
    QwenNlpEnginePrivate();
    ~QwenNlpEnginePrivate();
    std::string engineName() const;
    bool isCloud() const { return true; }
    bool isBuiltInEngine() const { return false; }
    bool isCustomModelEngine() const { return false; }

    void setConfig(const std::string &config);
    bool setCurrentModel(const std::string &model);
    std::string currentModel() const { return currentModel_; }
    std::string currentModelName() const { return currentModelName_; }
    std::string modelInfo() const;

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

    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:
    void addContext(const std::string &role, const std::string &content);
    ai_engine::result::AiEngineBaseResult buildChatMessage(const std::string &message);
    void clearContext();
    void removeLastContext();

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

    ai_engine::result::AiEngineBaseResult processChatResponse(cpr::Response &response);

    bool waitForStopped();

private:
    std::string apiKey_;
    std::string currentModel_{"qwen-plus"};
    std::string currentModelName_{"通义千问-qwen-plus"};
    int maxTokens_;

    ai_engine::gen_ai::nlp::TextGenerationResultCallback textGenerationResultCallback_{nullptr};

    Json::Value context_;
    int sentenceId_{0};

    std::vector<Json::Value> streamChatData_;
    std::string tempStreamChatData_;

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

    std::atomic<bool> isStopped_{false};
    bool isChatRunning_{false};
};

#endif  // QWENNLPENGINE_P_H
