/*
 * 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, ai_engine::ErrorCode> visionPrompt2ImageErrorCodeMap = 
{
    {1, ai_engine::ErrorCode::ServiceError},
    {2, ai_engine::ErrorCode::ServiceError},
    {4, ai_engine::ErrorCode::RequestFailed},
    {6, ai_engine::ErrorCode::AuthenticationFailed},
    {13, ai_engine::ErrorCode::RequestTooMany},
    {15, ai_engine::ErrorCode::RequestTooMany},
    {17, ai_engine::ErrorCode::RequestFailed},
    {18, ai_engine::ErrorCode::RequestTooMany},
    {19, ai_engine::ErrorCode::RequestFailed},
    {100, ai_engine::ErrorCode::AuthenticationFailed},
    {110, ai_engine::ErrorCode::AuthenticationFailed},
    {111, ai_engine::ErrorCode::AuthenticationFailed},
    {500, ai_engine::ErrorCode::ServiceError},
    {216100, ai_engine::ErrorCode::ParamError},
    {216303, ai_engine::ErrorCode::TaskTimeout},
    {216401, ai_engine::ErrorCode::RequestTooMany},
    {216630, ai_engine::ErrorCode::ServiceError},
    {282004, ai_engine::ErrorCode::ResultBlocked},
    {282352, ai_engine::ErrorCode::RequestFailed},
    {282501, ai_engine::ErrorCode::InputTextInvalid}
};

};

int server_error::parseErrorCode(const std::string &result)
{
    Json::Value obj = util::formatJsonFromString(result);
    if (!obj.isObject() || obj.isNull()) {
        return 0;
    }
    if (obj.isMember("error_code") && obj.isMember("error_msg")) {
        return obj["error_code"].asInt();
    }
    if (obj.isMember("err_msg") && obj.isMember("err_no")) {
        return obj["err_no"].asInt();
    }
    return 0;
}

const ai_engine::ErrorCode server_error::errorCode2visionResult(int errorCode)
{
    if (visionPrompt2ImageErrorCodeMap.count(errorCode) > 0) {
        return visionPrompt2ImageErrorCodeMap.at(errorCode);
    }

    fprintf(stderr, "Unknown error code: %d.\n", errorCode);

    return ai_engine::ErrorCode::RequestFailed;
}
