#include "deepseekai.h"
#include "deepseekconversation.h"
#include "deepseekcompletion.h"

UOSAI_USE_NAMESPACE

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

}

QJsonObject DeepSeekAI::predict(const QString &content, const QJsonArray &functions)
{
    Q_UNUSED(functions)

    DeepSeekConversation conversation;
    conversation.addUserData(content);
    conversation.filterThink();

    qreal temperature = m_params.value(PREDICT_PARAM_TEMPERATURE, 1.0).toReal();

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

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

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

    return response;
}

QPair<int, QString> DeepSeekAI::verify()
{
    DeepSeekConversation conversation;
    conversation.addUserData("Account verification only, no need for any response.");

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

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

    return errorpair;
}

void DeepSeekAI::onReadyReadChatDeltaContent(const QByteArray &content)
{
    if (content.isEmpty() || !stream())
        return;

    const QJsonObject &deltacontent = DeepSeekConversation::parseContentString(QString::fromUtf8(content));

    bool hasThinkChain = m_params.value(PREDICT_PARAM_THINKCHAIN, true).toBool();
    if (hasThinkChain) {
        readyThinkChainContent(deltacontent);
        return;
    }

    if (deltacontent.contains("content"))
        emit readyReadChatDeltaContent(deltacontent.value("content").toString());
}
