import mermaid from "mermaid";
import sanitize_html from "sanitize-html";
function ensureArray(data) {
    if (Array.isArray(data)) return data;
    if (data instanceof Map) return Array.from(data.values());
    if (data && 'object' == typeof data) return Object.values(data);
    return [];
}
function getNodeType(nodeLabel) {
    const lowerLabel = nodeLabel.toLowerCase();
    if (lowerLabel.includes('agent')) return 'agent';
    if (lowerLabel.includes('tool') || lowerLabel.includes('function')) return 'resource';
    if (lowerLabel.includes('context') || lowerLabel.includes('knowledge')) return 'resource';
    if (lowerLabel.includes('escalation') || lowerLabel.includes('human')) return 'resource';
    return 'flow';
}
async function mermaidToReactFlow(mermaidText) {
    try {
        mermaid.initialize({
            startOnLoad: false
        });
        const parseResult = await mermaid.parse(mermaidText, {
            suppressErrors: true
        });
        if (!parseResult) throw new Error('Invalid mermaid syntax');
        const diagram = await mermaid.mermaidAPI.getDiagramFromText(mermaidText);
        let rawNodes = [];
        let rawEdges = [];
        if (diagram && diagram.db) {
            rawNodes = ensureArray(diagram.db.getVertices());
            rawEdges = ensureArray(diagram.db.getEdges());
        }
        if (0 === rawNodes.length) throw new Error('Unable to extract nodes from diagram');
        const edges = rawEdges.map((mermaidEdge)=>({
                id: crypto.randomUUID(),
                source: mermaidEdge.start,
                target: mermaidEdge.end,
                type: 'default',
                label: mermaidEdge.text,
                animated: false,
                markerEnd: 'arrow',
                style: {
                    stroke: 'var(--canvas-foreground-de-emp)',
                    strokeWidth: 1
                },
                data: {
                    label: mermaidEdge.text,
                    raw: mermaidEdge
                }
            }));
        const nodes = rawNodes.map((mermaidNode)=>{
            let label = mermaidNode.text;
            if ('string' == typeof label && label.includes('<')) label = sanitize_html(label, {
                allowedTags: [],
                allowedAttributes: {}
            });
            const nodeType = getNodeType(label);
            return {
                id: mermaidNode.id,
                position: {
                    x: 0,
                    y: 0
                },
                type: nodeType,
                data: {
                    label,
                    raw: mermaidNode
                }
            };
        });
        return {
            nodes,
            edges
        };
    } catch  {
        return {
            nodes: [],
            edges: []
        };
    }
}
export { mermaidToReactFlow };
