#include "deepseekconversation.h"

#include <QJsonDocument>
#include <QRegularExpressionMatchIterator>
#include <QDebug>

UOSAI_USE_NAMESPACE

DeepSeekConversation::DeepSeekConversation()
{

}

QJsonObject DeepSeekConversation::parseContentString(const QString &content)
{
    QString result;
    QString reasoningContent;

    QRegularExpression regex(R"(data:\s*\{(.*)\})");
    QRegularExpressionMatchIterator iter = regex.globalMatch(content);

    while (iter.hasNext()) {
        QRegularExpressionMatch match = iter.next();
        QString matchString = match.captured(0);

        int startIndex = matchString.indexOf('{');
        int endIndex = matchString.lastIndexOf('}');

        if (startIndex >= 0 && endIndex > startIndex) {
            QString matchContent = matchString.mid(startIndex, endIndex - startIndex + 1);
            QJsonObject rootObject = QJsonDocument::fromJson(matchContent.toUtf8()).object();
            if (!rootObject.contains("choices"))
                continue;
            QJsonArray choicesArray = rootObject["choices"].toArray();
            if (choicesArray.isEmpty())
                continue;
            QJsonObject choiceObject = choicesArray.at(0).toObject();
            if (!choiceObject.contains("delta"))
                continue;
            QJsonObject deltaObject = choiceObject["delta"].toObject();

            if (deltaObject.contains("content")) {
                result += deltaObject.value("content").toString();
            }
            if (deltaObject.contains("reasoning_content")) {
                reasoningContent += deltaObject.value("reasoning_content").toString();
            }
        }
    }

    QJsonObject response;
    if (!result.isEmpty()) {
        response["content"] = result;
    }

    if (!reasoningContent.isEmpty()) {
        response["reasoningContent"] = reasoningContent;
    }

    return response;
}

void DeepSeekConversation::update(const QByteArray &response)
{
    if (response.isEmpty())
        return;

    const QJsonObject &delateData = parseContentString(response);
    if (delateData.contains("content")) {
        m_conversion.push_back(QJsonObject({
            { "role",    "assistant"    },
            { "content", delateData.value("content") }
        }));
    }
}
