/*
 * 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 "servererror.h"
#include "util.h"

namespace {

const std::map<int, std::tuple<ai_engine::EngineErrorCategory,
                               ai_engine::VisionEngineErrorCode>>
visionPrompt2ImageErrorCodeMap = {
    {10003,
     {ai_engine::EngineErrorCategory::InputError,
      ai_engine::VisionEngineErrorCode::InvalidParamType}},
    {10004,
     {ai_engine::EngineErrorCategory::InputError,
      ai_engine::VisionEngineErrorCode::InvalidParamType}},
    {10005,
     {ai_engine::EngineErrorCategory::InputError,
      ai_engine::VisionEngineErrorCode::InvalidParamType}},
    {10008,
     {ai_engine::EngineErrorCategory::InputError,
      ai_engine::VisionEngineErrorCode::TooManyRequest}},
    {10110,
     {ai_engine::EngineErrorCategory::OutputError,
      ai_engine::VisionEngineErrorCode::ImageCensorshipFailed}},
    {10021,
     {ai_engine::EngineErrorCategory::InputError,
      ai_engine::VisionEngineErrorCode::ImageCensorshipFailed}},
    {10022,
     {ai_engine::EngineErrorCategory::OutputError,
      ai_engine::VisionEngineErrorCode::ImageCensorshipFailed}},
    {11202,
     {ai_engine::EngineErrorCategory::OutputError,
      ai_engine::VisionEngineErrorCode::TooFrequentRequest}}
};

};

int xunfei_vision_server_error::parseErrorCode(const std::string &result) {
    Json::Value obj = xunfei_vision_util::formatJsonFromString(result);
    if (!obj.isObject() || obj.isNull()) {
        return 0;
    }
    if (obj.isMember("header") && obj["header"].isMember("code") &&
        obj["header"].isMember("message")) {
        return obj["header"]["code"].asInt();
    }
    return 0;
}

std::tuple<ai_engine::EngineErrorCategory, ai_engine::VisionEngineErrorCode>
xunfei_vision_server_error::errorCode2visionResult(int errorCode) {
    if (visionPrompt2ImageErrorCodeMap.count(errorCode) > 0) {
        return visionPrompt2ImageErrorCodeMap.at(errorCode);
    }
    return std::make_tuple(
        ai_engine::EngineErrorCategory::OutputError,
        ai_engine::VisionEngineErrorCode::ImageGenerationFailed);
}
