import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import React from 'react';
import { useMcpServers } from './McpContext';
import { useMcp } from 'react-mcp-hook';
const SlashCommandPromptContext = React.createContext(undefined);
const SlashCommandResolverBridge = ({ serverId, options, registration }) => {
    const connectionOptions = React.useMemo(() => {
        if (!options?.url || (options.serverEnabled === false)) {
            return null;
        }
        return {
            url: options.url,
            headers: options.headers,
            fetchTimeoutMs: options.fetchTimeoutMs,
            autoFetch: false
        };
    }, [options]);
    const mcp = useMcp(connectionOptions);
    const getPrompt = mcp.getPrompt;
    const resolver = React.useCallback(async (promptName, args) => {
        if (!connectionOptions) {
            throw new Error('MCP server is not configured correctly for prompts.');
        }
        if (typeof getPrompt !== 'function') {
            throw new Error('Prompt execution is not supported for this MCP server.');
        }
        const sanitizedArgs = Object.fromEntries(Object.entries(args ?? {}).flatMap(([key, value]) => {
            if (typeof value !== 'string') {
                return [];
            }
            const trimmed = value.trim();
            if (trimmed.length === 0) {
                return [];
            }
            return [[key, trimmed]];
        }));
        const hasArguments = Object.keys(sanitizedArgs).length > 0;
        const requestArgs = hasArguments
            ? sanitizedArgs
            : { __mcp_empty_arguments__: undefined };
        const result = await getPrompt(promptName, requestArgs);
        if (result.error) {
            throw result.error;
        }
        return result.prompt;
    }, [connectionOptions, getPrompt]);
    React.useEffect(() => {
        if (!connectionOptions || typeof getPrompt !== 'function') {
            registration.unregister(serverId);
            return;
        }
        registration.register(serverId, resolver);
        return () => {
            registration.unregister(serverId);
        };
    }, [connectionOptions, getPrompt, registration, resolver, serverId]);
    return null;
};
export const SlashCommandPromptProvider = ({ children }) => {
    const { servers } = useMcpServers();
    const resolverMapRef = React.useRef(new Map());
    const register = React.useCallback((serverId, resolver) => {
        resolverMapRef.current.set(serverId, resolver);
    }, []);
    const unregister = React.useCallback((serverId) => {
        resolverMapRef.current.delete(serverId);
    }, []);
    const resolvePrompt = React.useCallback(async (serverId, promptName, args) => {
        const resolver = resolverMapRef.current.get(serverId);
        if (!resolver) {
            throw new Error('No MCP prompt resolver is available for the selected slash command.');
        }
        return await resolver(promptName, args);
    }, []);
    const registration = React.useMemo(() => ({ register, unregister }), [register, unregister]);
    return (_jsxs(SlashCommandPromptContext.Provider, { value: { resolvePrompt }, children: [children, servers.map((server) => (_jsx(SlashCommandResolverBridge, { serverId: server.id, options: server.options, registration: registration }, server.id)))] }));
};
export const useSlashCommandPromptResolver = () => {
    const context = React.useContext(SlashCommandPromptContext);
    if (!context) {
        throw new Error('useSlashCommandPromptResolver must be used within a SlashCommandPromptProvider');
    }
    return context;
};
