// SPDX-FileCopyrightText: 2024 UnionTech Software Technology Co., Ltd.
//
// SPDX-License-Identifier: GPL-3.0-or-later

#include "deepseekfree.h"
#include "deepseekconversation.h"
#include "deepseekcompletion.h"

UOSAI_USE_NAMESPACE

DeepSeekFree::DeepSeekFree(const LLMServerProxy &serverproxy)
    : DeepSeekAI(serverproxy)
{

}

QJsonObject DeepSeekFree::predict(const QString &content, const QJsonArray &functions)
{
    DeepSeekConversation conversation;
    conversation.addUserData(content);
    conversation.filterThink();

    qreal temperature = m_params.value(PREDICT_PARAM_TEMPERATURE, 1.0).toReal();
    bool hasThink = m_params.value(PREDICT_PARAM_THINKCHAIN).toBool();
    bool enableOnlineSearch = m_params.value(PREDICT_PARAM_ONLINESEARCH).toBool();
    QString model = modelId();

    if (!functions.isEmpty()) {
        // 只有选择指令后才会带入Functions
        // 选择指令功能后强制调用V3模型
        model = v3Id();
        conversation.setFunctions(functions);
    } else if (enableOnlineSearch) {
        return onlineSearch(content);
    } else if (!hasThink) {
        model = v3Id();
    }

    DeepSeekCompletion chatCompletion(baseUrl(), m_accountProxy.account);
    connect(this, &DeepSeekAI::aborted, &chatCompletion, &DeepSeekCompletion::requestAborted);
    connect(&chatCompletion, &DeepSeekCompletion::readyReadDeltaContent, this, &DeepSeekFree::onReadyReadChatDeltaContent);

    QPair<int, QString> errorpair = chatCompletion.create(model, conversation, temperature);
    setLastError(errorpair.first);
    setLastErrorString(errorpair.second);

    QJsonObject response;
    response["content"] = conversation.getLastResponse();

    QJsonObject tools = conversation.getLastTools();
    if (!tools.isEmpty()) {
        response["tools"] = tools;
    }

    return response;
}

QJsonObject DeepSeekFree::onlineSearch(const QString &content)
{
    DeepSeekConversation conversation;
    conversation.addUserData(content);
    conversation.filterThink();

    DeepSeekCompletion chatCompletion(searchUrl(), m_accountProxy.account);
    connect(this, &DeepSeekAI::aborted, &chatCompletion, &DeepSeekCompletion::requestAborted);
    connect(&chatCompletion, &DeepSeekCompletion::readyReadDeltaContent, this, &DeepSeekFree::onReadyReadChatDeltaContent);

    bool hasThink = m_params.value(PREDICT_PARAM_THINKCHAIN).toBool();
    const QString botId = hasThink ? searchR1Id() : searchV3Id();

    QPair<int, QString> errorpair = chatCompletion.create(botId, conversation, 1.0);
    setLastError(errorpair.first);
    setLastErrorString(errorpair.second);

    QJsonObject response;
    response["content"] = conversation.getLastResponse();

    return response;
}
