/*
 * 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 "baiduvisionengine_p.h"
#include <unistd.h>
#include <map>
#include <cpr/cpr.h>
#include "baiduresponseprocessor.h"
#include "imageloader.h"
#include "servererror.h"
#include "token.h"
#include "util.h"

namespace {
std::map<int, std::string> imageStyleMap = {
    {0, "探索无限"},    {1, "古风"},     {2, "二次元"},      {3, "写实风格"},
    {4, "浮世绘"},      {5, "low poly"}, {6, "未来主义"},    {7, "像素风格"},
    {8, "概念艺术"},    {9, "赛博朋克"}, {10, "洛丽塔风格"}, {11, "巴洛克风格"},
    {12, "超现实主义"}, {13, "水彩画"},  {14, "蒸汽波艺术"}, {15, "油画"},
    {16, "卡通画"},
};
}

BaiduVisionEnginePrivate::BaiduVisionEnginePrivate() {}

BaiduVisionEnginePrivate::~BaiduVisionEnginePrivate() {}

std::string BaiduVisionEnginePrivate::engineName() const {
    return std::string("baidu");
}

std::string BaiduVisionEnginePrivate::currentModel() const {
    return currentModel_;
}

bool BaiduVisionEnginePrivate::setCurrentModel(const std::string &model) {
    Json::Value modelInfoJson =
        baidu_vision_util::formatJsonFromString(modelInfo());
    for (auto &item : modelInfoJson["models"]) {
        if (item["model"].asString() == model) {
            currentModel_ = model;
            return true;
        }
    }
    fprintf(stderr, "Invalid current model name: %s\n", model.c_str());
    return false;
}

void BaiduVisionEnginePrivate::setConfig(const std::string &config) {
    Json::Value configJson = baidu_vision_util::formatJsonFromString(config);
    if (configJson.isNull() || !configJson.isMember("apiKey") ||
        !configJson.isMember("secretKey") || !configJson["apiKey"].isString() ||
        !configJson["secretKey"].isString()) {
        std::fprintf(stderr, "Invalid config for baidu vision engine: %s\n",
                     config.c_str());
        return;
    }
    apiKey_ = configJson["apiKey"].asString();
    secretKey_ = configJson["secretKey"].asString();
}

std::string BaiduVisionEnginePrivate::modelInfo() const {
    const char *info = R"(
    {
        "vendor": "百度",
        "models": [
            {
                "name": "百度-文心AI作画高级版",
                "model": "百度-文心AI作画高级版",
                "subConfig": [
                    {
                        "name": "文心AI作画高级版",
                        "config": [
                            {
                                "friendlyName": "APIKey",
                                "configName": "apiKey"
                            },
                            {
                                "friendlyName": "APISecret",
                                "configName": "secretKey"
                            }
                        ]
                    }
                ],
                "is3rdModel": true,
                "feedbackUrl": "https://cloud.baidu.com/doc/support/index.html"
            }
        ]
    }
    )";

    return info;
}

void BaiduVisionEnginePrivate::setGenerationResultCallback(
    ai_engine::gen_ai::vision::ImageGenerationCallback callback) {
    imageGenerationResultCallback_ = callback;
}

void BaiduVisionEnginePrivate::setImageSize(int width, int height) {
    auto isSupporedSize = [this](const int inputWidth,
                                 const int inputHeight) -> bool {
        for (const auto &item : supportedImageSizes()) {
            if (item.first == inputWidth && item.second == inputHeight) {
                return true;
            }
        }
        return false;
    };
    if (width <= 0 || height <= 0 || !isSupporedSize(width, height)) {
        currentError_ = ai_engine::EngineError(
            static_cast<int>(
                ai_engine::VisionEngineErrorCode::ImageSizeInvalid),
            "Unsupported size of images");
        imageWidth_ = -1;
        imageHeight_ = -1;
        return;
    }
    imageWidth_ = width;
    imageHeight_ = height;
}

void BaiduVisionEnginePrivate::setImageNumber(int number) {
    if (number > supportedImageNumber() || number <= 0) {
        currentError_ = ai_engine::EngineError(
            static_cast<int>(
                ai_engine::VisionEngineErrorCode::ImageNumberInvalid),
            "Unsupported number of images");
        imageNumber_ = -1;
        return;
    }
    imageNumber_ = number;
}

void BaiduVisionEnginePrivate::setImageStyle(const std::string &style) {
    imageStyle_ = style;
}

std::vector<std::string>
BaiduVisionEnginePrivate::supportedImageStyles() const {
    return {"探索无限",   "古风",       "二次元",     "写实风格", "浮世绘",
            "low poly",   "未来主义",   "像素风格",   "概念艺术", "赛博朋克",
            "洛丽塔风格", "巴洛克风格", "超现实主义", "水彩画",   "蒸汽波艺术",
            "油画",       "卡通画"};
}

int BaiduVisionEnginePrivate::supportedImageNumber() const { return 8; }

std::vector<std::pair<int, int>>
BaiduVisionEnginePrivate::supportedImageSizes() const {
    std::vector<std::pair<int, int>> result{
        {512, 512},  {640, 360},   {360, 640},   {1024, 1024}, {1280, 720},
        {720, 1280}, {2048, 2048}, {2560, 1440}, {1440, 2560}};
    return result;
}

void BaiduVisionEnginePrivate::stopImageGeneration() {
    if (isStopped_.exchange(true)) {
        return;
    }
    if (isGenerating_) {
        ai_engine::gen_ai::vision::ImageGenerationResult data{
            true, currentError_, currentModelName_, 0, 0, 1, 1, "", ""};
        imageGenerationResultCallback_(data);
        isGenerating_ = false;
    }
}

ai_engine::result::AiEngineBaseResult
BaiduVisionEnginePrivate::generateImage(const std::string &prompt) {
    isStopped_ = false;
    if (!imageGenerationResultCallback_) {
        return {false, currentError_};
    }
    if (imageNumber_ == -1 || imageHeight_ == -1 || imageWidth_ == -1) {
        return {false, currentError_};
    }
    if (prompt.empty()) {
        currentError_ = ai_engine::EngineError(
            (int)ai_engine::VisionEngineErrorCode::TooLittleData,
            "The prompt is empty");
        return {false, currentError_};
    }

    if (!generateAccessToken_()) {
        return {false, currentError_};
    }
    isGenerating_ = true;
    std::string taskId = requestPrompt2ImageTask(prompt);
    if (taskId.empty()) {
        if (isStopped_) {
            return {true, currentError_};
        }
        return {false, currentError_};
    }
    return processPrompt2ImageTask(taskId);
}

std::string &BaiduVisionEnginePrivate::getAccessToken_() {
    if (accessToken_.empty()) {
        generateAccessToken_();
    }
    return accessToken_;
}

bool BaiduVisionEnginePrivate::generateAccessToken_() {
    bool hasNetError = false;
    std::string errorMessage;
    accessToken_ = baidu_vision_token::getBaiduToken(apiKey_, secretKey_,
                                                     hasNetError, errorMessage);
    if (accessToken_.empty()) {
        fprintf(stderr, "get baidu token failed: %s\n", errorMessage.c_str());
        if (hasNetError) {
            currentError_ = ai_engine::EngineError(
                (int)ai_engine::VisionEngineErrorCode::NetworkDisconnected,
                errorMessage);
        } else {
            currentError_ = ai_engine::EngineError(
                (int)ai_engine::VisionEngineErrorCode::Unauthorized,
                errorMessage);
        }
        return false;
    }
    return true;
}

std::string
BaiduVisionEnginePrivate::requestPrompt2ImageTask(const std::string &prompt) {
    const std::string postUrl{"https://aip.baidubce.com/rpc/2.0/ernievilg/v1/"
                              "txt2imgv2?access_token=" +
                              getAccessToken_()};

    Json::Value postJson;
    if (imageStyle_.empty()) {
        postJson["prompt"] = std::string(prompt);
    } else if (imageStyle_ == "low poly") {
        postJson["prompt"] = std::string(prompt) + "，" + "低多边形";
    } else {
        postJson["prompt"] = std::string(prompt) + "，" + imageStyle_;
    }
    postJson["width"] = imageWidth_;
    postJson["height"] = imageHeight_;
    postJson["image_num"] = imageNumber_;
    std::string postString = postJson.toStyledString();

    cpr::Url url{postUrl};
    cpr::Header header{{"Content-Type", "application/json"},
                       {"Accept", "application/json"}};
    cpr::Body body{postString};

    auto future = cpr::PostAsync(url, header, body);

    while (future.wait_for(std::chrono::milliseconds(100)) !=
           std::future_status::ready) {
        if (isStopped_) {
            return std::string();
        }
    }

    cpr::Response r = future.get();

    if (r.error) {
        fprintf(stderr, "net error: %s\n", r.error.message.c_str());
        currentError_ = ai_engine::EngineError(
            (int)ai_engine::VisionEngineErrorCode::NetworkDisconnected,
            r.error.message);
        return std::string();
    }

    if (int errorCode = baidu_vision_server_error::parseErrorCode(r.text)) {
        fprintf(stderr, "baidu request text2image task failed: %s\n",
                r.text.c_str());
        auto erroraTuple =
            baidu_vision_server_error::errorCode2visionResult(errorCode);
        currentError_ =
            ai_engine::EngineError((int)std::get<1>(erroraTuple), r.text);
        return std::string();
    }

    Json::Value result = baidu_vision_util::formatJsonFromString(r.text);

    if (baidu_vision_token::isBaiduTokenExpiredByResult(result)) {
        generateAccessToken_();
        return requestPrompt2ImageTask(prompt);
    }

    return result["data"]["task_id"].asString();
}

ai_engine::result::AiEngineBaseResult
BaiduVisionEnginePrivate::processPrompt2ImageTask(const std::string &taskId) {
    while (1) {
        const std::string taskResult = doRequestTaskResult(taskId);
        if (taskResult.empty()) {
            if (isStopped_ == true) {
                return {true, currentError_};
            }
            runCallbackWithError(currentError_, imageNumber_, imageNumber_);
            return {false, currentError_};
        }

        ImageDataList list;
        bool isTaskBlocked = false;
        std::string errorMessage;
        ProcessResult processCode = BaiduResponseProcessor::process(
            taskResult, list, isTaskBlocked, errorMessage);

        if (processCode == ProcessResult::SUCCEEDED) {
            for (auto &imageData : list) {
                if (isStopped_ == true) {
                    return {true, currentError_};
                }
                auto imageInfo = vision::image_loader::getImageInfoFromData(
                    imageData.data_.data(), imageData.data_.size());
                std::vector<char> charDataVector;
                for (unsigned char value : imageData.data_) {
                    charDataVector.push_back(static_cast<char>(value));
                }
                std::string imageDataString{imageData.data_.begin(),
                                            imageData.data_.end()};
                ai_engine::gen_ai::vision::ImageGenerationResult data{
                    true,
                    currentError_,
                    currentModelName_,
                    imageInfo.width,
                    imageInfo.height,
                    (int)imageData.index_,
                    (int)list.size(),
                    imageInfo.format,
                    baidu_vision_util::base64Encode(imageDataString)};
                if (imageData.conclusion_ == ApproveConclusion::BLOCK) {
                    data.success = false;
                    data.error = ai_engine::EngineError(
                        (int)ai_engine::VisionEngineErrorCode::
                            ImageCensorshipFailed,
                        errorMessage);
                    fprintf(stderr, "baidu image censorship failed: "
                                    "imageData.conclusion_ is block\n");
                } else {
                    ai_engine::EngineError error;
                    data.error = error;
                }
                imageGenerationResultCallback_(data);
                isGenerating_ = false;
            }
            return {true, currentError_};
        }

        if (processCode == ProcessResult::FAILED) {
            if (isTaskBlocked) {
                currentError_ = ai_engine::EngineError(
                    (int)
                        ai_engine::VisionEngineErrorCode::ImageCensorshipFailed,
                    errorMessage);
            } else {
                currentError_ = ai_engine::EngineError(
                    (int)
                        ai_engine::VisionEngineErrorCode::ImageGenerationFailed,
                    errorMessage);
            }
            runCallbackWithError(currentError_, imageNumber_, imageNumber_);
            return {false, currentError_};
        }
        sleep(1);
    }
}

std::string
BaiduVisionEnginePrivate::doRequestTaskResult(const std::string &taskId) {
    const std::string postUrl{
        "https://aip.baidubce.com/rpc/2.0/ernievilg/v1/getImgv2?access_token=" +
        getAccessToken_()};

    char postData[1024];
    snprintf(postData, sizeof(postData), "{\"task_id\":\"%s\"}",
             taskId.c_str());

    cpr::Url url{postUrl};
    cpr::Header header{{"Content-Type", "application/json"},
                       {"Accept", "application/json"}};
    cpr::Body body{postData};
    auto future = cpr::PostAsync(url, header, body);

    while (future.wait_for(std::chrono::milliseconds(100)) !=
           std::future_status::ready) {
        if (isStopped_) {
            return std::string();
        }
    }

    cpr::Response r = future.get();

    if (r.error) {
        fprintf(stderr, "net error: %s\n", r.error.message.c_str());
        currentError_ = ai_engine::EngineError(
            (int)ai_engine::VisionEngineErrorCode::NetworkDisconnected,
            r.error.message);
        return std::string();
    }

    if (baidu_vision_token::isBaiduTokenExpiredByResult(r.text)) {
        generateAccessToken_();
        return doRequestTaskResult(taskId);
    }

    if (int errorCode = baidu_vision_server_error::parseErrorCode(r.text)) {
        fprintf(stderr, "baidu request text2image result failed: %s\n",
                r.text.c_str());
        auto erroraTuple =
            baidu_vision_server_error::errorCode2visionResult(errorCode);
        currentError_ =
            ai_engine::EngineError((int)std::get<1>(erroraTuple), r.text);
        return std::string();
    }

    return r.text;
}

void BaiduVisionEnginePrivate::runCallbackWithError(
    const ai_engine::EngineError &error, const int &index, const int &total) {
    int errorValue = 0;
    if (index == total) {
        for (int i = 0; i < total; i++) {
            ai_engine::gen_ai::vision::ImageGenerationResult data{
                false,      error,      currentModelName_,
                errorValue, errorValue, i,
                total,      "",         ""};
            imageGenerationResultCallback_(data);
        }
        isGenerating_ = false;
    } else {
        ai_engine::gen_ai::vision::ImageGenerationResult data{
            false,      error,      currentModelName_,
            errorValue, errorValue, index,
            total,      "",         ""};
        imageGenerationResultCallback_(data);
        isGenerating_ = false;
    }
}
