// 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)
{
    bool enableOnlineSearch = m_params.value(PREDICT_PARAM_ONLINESEARCH).toBool();
    if (enableOnlineSearch)
        return onlineSearch(content);

    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();
    QString model = modelId();

    if (!hasThink)
        model = v3Id();

    if (!functions.isEmpty()) {
        model = v3Id();
        conversation.setFunctions(functions);
    }

    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;
}
