#include "deepseekcompletion.h"
#include "servercodetranslation.h"

UOSAI_USE_NAMESPACE

DeepSeekCompletion::DeepSeekCompletion(const QString &url, const AccountProxy &account)
    : BaseNetWork(account)
    , rootUrl(url)
{

}

QPair<int, QString> DeepSeekCompletion::create(const QString &model, DeepSeekConversation &conversation, qreal temperature)
{
    Q_UNUSED(temperature)

    QJsonObject dataObject;
    QJsonArray conversions = conversation.getConversions();
    if (!conversation.getFunctions().isEmpty()) {
        dataObject.insert("tools", transformFunctionList(conversation.getFunctions()));
    }
    dataObject.insert("messages", conversions);
    dataObject.insert("stream", true);
    dataObject.insert("model", model);
    auto baseresult = request(QUrl(rootUrl), dataObject, nullptr);

    if (baseresult.error != AIServer::NoError) {
        baseresult.data = ServerCodeTranslation::serverCodeTranslation(baseresult.error, baseresult.errorString).toUtf8();
        return qMakePair(baseresult.error, baseresult.data);
    }

    conversation.update(baseresult.data);
    return qMakePair(0, QString());
}

QJsonArray DeepSeekCompletion::transformFunctionList(const QJsonArray &inputArray) {
    QJsonArray outputArray;

    for (const QJsonValue &value : inputArray) {
        if (!value.isObject()) continue;
        QJsonObject obj = value.toObject();

        QJsonObject wrapperObject;
        wrapperObject["type"] = "function";
        wrapperObject["function"] = obj;

        outputArray.append(wrapperObject);
    }

    return outputArray;
}
