import { MetadataMode, TextNode } from "../Node.js";
export class MarkdownNodeParser {
    includeMetadata;
    includePrevNextRel;
    constructor(init){
        this.includeMetadata = init?.includeMetadata ?? true;
        this.includePrevNextRel = init?.includePrevNextRel ?? true;
    }
    async transform(nodes, _options) {
        return this.getNodesFromDocuments(nodes);
    }
    static fromDefaults(init) {
        return new MarkdownNodeParser(init);
    }
    buildNodeFromSplit(textSplit, node, metadata) {
        const newNode = new TextNode({
            text: textSplit,
            relationships: {
                PARENT: [
                    {
                        ...node,
                        nodeId: node.id_
                    }
                ]
            },
            metadata: this.includeMetadata ? metadata : {}
        });
        return newNode;
    }
    updateMetadata(headersMetadata, newHeader, newHeaderLevel) {
        const updatedHeaders = {};
        for(let i = 1; i < newHeaderLevel; i++){
            const key = `Header ${i}`;
            if (key in headersMetadata) {
                updatedHeaders[key] = headersMetadata[key];
            }
        }
        updatedHeaders[`Header ${newHeaderLevel}`] = newHeader;
        return updatedHeaders;
    }
    getNodesFromNode(node) {
        const text = node.getContent(MetadataMode.NONE);
        const markdownNodes = [];
        const lines = text.split("\n");
        let metadata = {};
        let codeBlock = false;
        let currentSection = "";
        for (const line of lines){
            if (line.startsWith("```")) {
                codeBlock = !codeBlock;
            }
            const headerMatch = line.match(/^(#+)\s(.*)/);
            if (headerMatch && !codeBlock) {
                if (currentSection !== "") {
                    markdownNodes.push(this.buildNodeFromSplit(currentSection.trim(), node, metadata));
                }
                metadata = this.updateMetadata(metadata, headerMatch[2], headerMatch[1].length);
                currentSection = `${headerMatch[2]}\n`;
            } else {
                currentSection += line + "\n";
            }
        }
        markdownNodes.push(this.buildNodeFromSplit(currentSection.trim(), node, metadata));
        return markdownNodes;
    }
    getNodesFromDocuments(documents) {
        let allNodes = [];
        for (const node of documents){
            const nodes = this.getNodesFromNode(node);
            allNodes = allNodes.concat(nodes);
        }
        return allNodes;
    }
}
