import { visit } from "unist-util-visit";
import { CHAT_CITATION_START } from "../../../../service/index.js";
function citationPlugin() {
    const citationStack = [];
    return (tree)=>{
        visit(tree, 'text', (node, _index, parent)=>{
            if (!node?.value || !parent) return;
            const text = String(node.value);
            const pattern = /\[\[cite-start:([^\]]+)\]\]|\[\[cite-end\]\]/g;
            const newChildren = [];
            let lastIndex = 0;
            let match;
            while(null !== (match = pattern.exec(text))){
                const before = text.slice(lastIndex, match.index);
                if (before) newChildren.push({
                    type: 'text',
                    value: before
                });
                const token = match[0];
                if (token.startsWith('[[cite-start:')) try {
                    const raw = atob(match[1]);
                    const decoded = raw.startsWith('%5B') ? decodeURIComponent(raw) : raw;
                    const citationsData = JSON.parse(decoded);
                    citationStack.push({
                        citationsData
                    });
                    newChildren.push({
                        type: 'element',
                        tagName: 'span',
                        data: {
                            hName: 'span',
                            hProperties: {
                                className: [
                                    CHAT_CITATION_START
                                ],
                                'data-citation-ids': citationsData.map((c)=>String(c.id)).join(' '),
                                style: 'display:none'
                            }
                        },
                        children: []
                    });
                } catch (e) {
                    console.error('[CitationPlugin] Failed to parse citation data:', e);
                }
                else {
                    const info = citationStack.pop();
                    if (info) {
                        const citationComponents = info.citationsData.map((citation)=>({
                                type: 'citation',
                                data: {
                                    hName: 'citation',
                                    hProperties: {
                                        id: citation.id,
                                        title: citation.title,
                                        url: citation.url,
                                        page_number: citation.page_number,
                                        download_url: citation.download_url,
                                        messageId: citation.messageId
                                    }
                                }
                            }));
                        newChildren.push(...citationComponents);
                    }
                }
                lastIndex = match.index + match[0].length;
            }
            if (lastIndex < text.length) newChildren.push({
                type: 'text',
                value: text.slice(lastIndex)
            });
            const nodeIndex = parent.children.indexOf(node);
            if (nodeIndex >= 0) parent.children.splice(nodeIndex, 1, ...newChildren);
        });
    };
}
function contentPartsToMarkdown(messageId, contentParts) {
    const markdown = contentParts.map((part, _index)=>{
        let text = part.text ?? '';
        if (part.citations && part.citations.length > 0) {
            const citationsData = part.citations.map((citation)=>({
                    id: citation.id,
                    title: citation.title,
                    url: 'url' in citation ? citation.url : void 0,
                    download_url: 'download_url' in citation ? citation.download_url : void 0,
                    page_number: 'page_number' in citation ? citation.page_number : void 0,
                    messageId
                }));
            const encodedData = btoa(encodeURIComponent(JSON.stringify(citationsData)));
            const endsWithUrl = /https?:\/\/\S+$/.test(text);
            text = `[[cite-start:${encodedData}]]${text}${endsWithUrl ? ' ' : ''}[[cite-end]]`;
        }
        return text;
    }).join('');
    return markdown;
}
export { citationPlugin, contentPartsToMarkdown };
