#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, const QString &systemRole, qreal temperature)
{
    Q_UNUSED(functions)
    Q_UNUSED(systemRole)

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

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

    if (hasThinkChain()) {
        readyThinkChainContent(deltacontent);
        return;
    }

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