import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useMCPStore } from '../stores/mcpStore';
import { API_BASE_URL } from '../lib/config';
import { useEffect, useRef, useCallback } from 'react';
async function fetchMCPServers() {
    const response = await fetch(`${API_BASE_URL}/v1/mcp/servers`);
    if (!response.ok)
        throw new Error('Failed to fetch MCP servers');
    return response.json();
}
export function useMCPServers() {
    const setServers = useMCPStore((s) => s.setServers);
    const query = useQuery({
        queryKey: ['mcp', 'servers'],
        queryFn: fetchMCPServers,
        refetchInterval: 10000,
    });
    useEffect(() => {
        if (query.data?.servers) {
            setServers(query.data.servers);
        }
    }, [query.data, setServers]);
    return query;
}
export function useStartMCPServer() {
    const queryClient = useQueryClient();
    return useMutation({
        mutationFn: async (name) => {
            const response = await fetch(`${API_BASE_URL}/v1/mcp/servers/${encodeURIComponent(name)}/start`, { method: 'POST' });
            const data = await response.json();
            if (!data.ok)
                throw new Error(data.error || 'Failed to start server');
            return data;
        },
        onSettled: () => {
            queryClient.invalidateQueries({ queryKey: ['mcp', 'servers'] });
        },
    });
}
export function useStopMCPServer() {
    const queryClient = useQueryClient();
    const setLoading = useMCPStore((s) => s.setLoading);
    return useMutation({
        mutationFn: async (name) => {
            setLoading(name, true);
            const response = await fetch(`${API_BASE_URL}/v1/mcp/servers/${encodeURIComponent(name)}/stop`, { method: 'POST' });
            const data = await response.json();
            if (!data.ok)
                throw new Error(data.error || 'Failed to stop server');
            return data;
        },
        onSettled: (_data, _error, name) => {
            setLoading(name, false);
            queryClient.invalidateQueries({ queryKey: ['mcp', 'servers'] });
        },
    });
}
export function useAddMCPServer() {
    const queryClient = useQueryClient();
    return useMutation({
        mutationFn: async (params) => {
            const response = await fetch(`${API_BASE_URL}/v1/mcp/servers`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(params),
            });
            const data = await response.json();
            if (!data.ok)
                throw new Error(data.error || 'Failed to add MCP server');
            return data;
        },
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['mcp', 'servers'] });
        },
    });
}
export function useRemoveMCPServer() {
    const queryClient = useQueryClient();
    return useMutation({
        mutationFn: async (name) => {
            const response = await fetch(`${API_BASE_URL}/v1/mcp/servers/${encodeURIComponent(name)}`, { method: 'DELETE' });
            const data = await response.json();
            if (!data.ok)
                throw new Error(data.error || 'Failed to remove MCP server');
            return data;
        },
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['mcp', 'servers'] });
        },
    });
}
export function useAuthenticateMCPServer() {
    const queryClient = useQueryClient();
    return useMutation({
        mutationFn: async (name) => {
            const response = await fetch(`${API_BASE_URL}/v1/mcp/servers/${encodeURIComponent(name)}/auth`, { method: 'POST' });
            const data = await response.json();
            if (!data.ok)
                throw new Error(data.error || 'Failed to initiate auth');
            return data;
        },
        onSettled: () => {
            queryClient.invalidateQueries({ queryKey: ['mcp', 'servers'] });
        },
    });
}
export function useRevokeMCPAuth() {
    const queryClient = useQueryClient();
    return useMutation({
        mutationFn: async (name) => {
            const response = await fetch(`${API_BASE_URL}/v1/mcp/servers/${encodeURIComponent(name)}/auth`, { method: 'DELETE' });
            const data = await response.json();
            if (!data.ok)
                throw new Error(data.error || 'Failed to revoke auth');
            return data;
        },
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['mcp', 'servers'] });
        },
    });
}
export function useMCPAuthStatus(name) {
    return useQuery({
        queryKey: ['mcp', 'auth', name],
        queryFn: async () => {
            if (!name)
                return { authenticated: false };
            const response = await fetch(`${API_BASE_URL}/v1/mcp/servers/${encodeURIComponent(name)}/auth/status`);
            return response.json();
        },
        enabled: !!name,
        refetchInterval: 3000,
    });
}
export function useCopilotDevicePoller() {
    const copilotDevice = useMCPStore((s) => s.copilotDevice);
    const setCopilotDevice = useMCPStore((s) => s.setCopilotDevice);
    const setLoading = useMCPStore((s) => s.setLoading);
    const queryClient = useQueryClient();
    const timerRef = useRef(null);
    const stopPolling = useCallback(() => {
        if (timerRef.current) {
            clearInterval(timerRef.current);
            timerRef.current = null;
        }
    }, []);
    useEffect(() => {
        if (!copilotDevice) {
            stopPolling();
            return;
        }
        const { sessionId, serverName, interval } = copilotDevice;
        const pollMs = (interval || 5) * 1000 + 1000;
        timerRef.current = setInterval(async () => {
            try {
                const response = await fetch(`${API_BASE_URL}/v1/mcp/servers/${encodeURIComponent(serverName)}/auth/callback`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ sessionId }),
                });
                const data = await response.json();
                if (data.status === 'complete') {
                    stopPolling();
                    setCopilotDevice(null);
                    setLoading(serverName, false);
                    queryClient.invalidateQueries({ queryKey: ['mcp', 'servers'] });
                }
                else if (data.status === 'error') {
                    stopPolling();
                    setCopilotDevice(null);
                    setLoading(serverName, false);
                }
            }
            catch {
                stopPolling();
                setCopilotDevice(null);
                setLoading(serverName, false);
            }
        }, pollMs);
        return stopPolling;
    }, [copilotDevice, setCopilotDevice, setLoading, queryClient, stopPolling]);
    return copilotDevice;
}
//# sourceMappingURL=useMCP.js.map