import { visit } from "unist-util-visit";
const RESOURCE_TOKEN_PATTERN = /\[\[resource-token:(.*?)\]\]/g;
const createTextNode = (value)=>({
        type: 'text',
        value
    });
const createResourceChipNode = (resource)=>({
        type: 'resource-chip',
        data: {
            hName: 'resource-chip',
            hProperties: {
                id: resource.id,
                type: resource.type,
                icon: resource.icon,
                displayName: resource.displayName
            }
        }
    });
const parseResourceData = (json)=>{
    try {
        const parsed = JSON.parse(json);
        if (!parsed?.id || !parsed?.type || !parsed?.displayName) return null;
        return parsed;
    } catch (e) {
        console.error('[ResourceTokenPlugin] Failed to parse resource token:', e);
        return null;
    }
};
function stripResourceTokens(text) {
    return text.replace(RESOURCE_TOKEN_PATTERN, (match, json)=>{
        const resource = parseResourceData(json);
        return resource?.displayName ?? match;
    });
}
function resourceTokenPlugin() {
    return (tree)=>{
        visit(tree, 'text', (node, _index, parent)=>{
            if (!node.value || !parent) return;
            const text = node.value;
            const matches = [
                ...text.matchAll(RESOURCE_TOKEN_PATTERN)
            ];
            if (0 === matches.length) return;
            const newChildren = [];
            let lastIndex = 0;
            for (const match of matches){
                const matchIndex = match.index ?? 0;
                const before = text.slice(lastIndex, matchIndex);
                if (before) newChildren.push(createTextNode(before));
                const resourceData = match[1] ? parseResourceData(match[1]) : null;
                newChildren.push(resourceData ? createResourceChipNode(resourceData) : createTextNode(match[0]));
                lastIndex = matchIndex + match[0].length;
            }
            const remaining = text.slice(lastIndex);
            if (remaining) newChildren.push(createTextNode(remaining));
            const nodeIndex = parent.children.indexOf(node);
            if (nodeIndex >= 0) parent.children.splice(nodeIndex, 1, ...newChildren);
        });
    };
}
export { resourceTokenPlugin, stripResourceTokens };
