#include "outlineparser.h"

#include <QDebug>
#include <QJsonDocument>
#include <QJsonObject>

OutlineParser::OutlineParser(QObject *parent)
    : QObject(parent)
{

}

void OutlineParser::parse(const QString &markdownText)
{
    qDebug() << "11111111111" << markdownText;

    m_nextId = 0;
    m_currentTopLevelNodeId = -1;
    m_isLookingForOverview = false;

    // 解析Markdown
    QByteArray mdUtf8 = markdownText.toUtf8();
    cmark_node* doc = cmark_parse_document(
        mdUtf8.constData(),  // 安全的UTF-8字节指针
        mdUtf8.size(),       // 精确的UTF-8字节长度（避免解析不完整）
        CMARK_OPT_DEFAULT
    );

    if (doc == nullptr) {
        return;
    }

    parseNodes(cmark_node_first_child(doc));
    cmark_node_free(doc);
    return;
}

void OutlineParser::parseNodes(cmark_node *node)
{
    while (node) {
        cmark_node_type nodeType = cmark_node_get_type(node);
        qDebug() << "---node_type---" << nodeType;

        if (nodeType == CMARK_NODE_HEADING) {
            // 处理标题节点
            int level = cmark_node_get_heading_level(node);
            QString text = extractText(node);
            qDebug() << "---heading_node---level---" << level << "text---" << text;

            if (level == 1 || level == 2) {
                // 处理一级或二级标题
                int newNodeId = m_nextId++;
                m_currentTopLevelNodeId = newNodeId;
                m_isLookingForOverview = true;

                QJsonObject jsonObj;
                jsonObj["id"] = newNodeId;
                jsonObj["level"] = level;
                jsonObj["title"] = text;
                jsonObj["overview"] = "";

                QJsonDocument doc(jsonObj);
                QString jsonString = doc.toJson(QJsonDocument::Compact);
                emit topLevelNodeParsed(jsonString);

            } else if (level >= 3 && level <= 4 && m_currentTopLevelNodeId != -1) {
                // 处理三级或四级标题
                int newChildId = m_nextId++;

                QJsonObject jsonObj;
                jsonObj["id"] = newChildId;
                jsonObj["level"] = level;
                jsonObj["title"] = text;

                QJsonDocument doc(jsonObj);
                QString jsonString = doc.toJson(QJsonDocument::Compact);
                // 发送信号时，带上父节点ID
                emit childNodeParsed(m_currentTopLevelNodeId, jsonString);
            }

        } else if ((nodeType == CMARK_NODE_PARAGRAPH || nodeType == CMARK_NODE_LIST) && m_isLookingForOverview) {
            // 处理概述 (段落或列表)
            QString overview = extractText(node);
            qDebug() << "---overview---text---" << overview;
            if (!overview.isEmpty()) {
                emit nodeOverviewUpdated(m_currentTopLevelNodeId, overview);
                m_isLookingForOverview = false;
            }
        }

        // 递归遍历子节点
        if (cmark_node_first_child(node)) {
            parseNodes(cmark_node_first_child(node));
        }

        // 移动到下一个兄弟节点
        node = cmark_node_next(node);
    }

    return;
}

QString OutlineParser::extractText(cmark_node *node)
{
    if (node == nullptr) {
        return "";
    }

    QString text;
    cmark_node* child = cmark_node_first_child(node);
    while (child) {
        if (cmark_node_get_type(child) == CMARK_NODE_TEXT) {
            const char* literal = cmark_node_get_literal(child);
            if (literal) {
                text += QString::fromUtf8(literal);
            }
        }

        child = cmark_node_next(child);
    }

    return text;
}
