/**
 * @license
 * Copyright 2025 Vybestack LLC
 * SPDX-License-Identifier: Apache-2.0
 */
import { CoreToolScheduler, DEFAULT_AGENT_ID, } from '@vybestack/llxprt-code-core';
import { useCallback, useState, useMemo, useEffect } from 'react';
import { ToolCallStatus, } from '../types.js';
export function useReactToolScheduler(onComplete, config, setPendingHistoryItem, getPreferredEditor, onEditorClose, onEditorOpen = () => { }) {
    const [toolCallsByScheduler, setToolCallsByScheduler] = useState(new Map());
    const updatePendingHistoryItem = useCallback((toolCallId, outputChunk) => {
        setPendingHistoryItem((prevItem) => {
            if (prevItem?.type === 'tool_group') {
                return {
                    ...prevItem,
                    tools: prevItem.tools.map((toolDisplay) => toolDisplay.callId === toolCallId &&
                        toolDisplay.status === ToolCallStatus.Executing
                        ? { ...toolDisplay, resultDisplay: outputChunk }
                        : toolDisplay),
                };
            }
            return prevItem;
        });
    }, [setPendingHistoryItem]);
    const updateToolCallsForScheduler = useCallback((schedulerId, updater) => {
        setToolCallsByScheduler((prev) => {
            const currentCalls = prev.get(schedulerId) ?? [];
            const updatedCalls = updater(currentCalls);
            if (updatedCalls === currentCalls) {
                return prev;
            }
            const next = new Map(prev);
            if (!updatedCalls || updatedCalls.length === 0) {
                next.delete(schedulerId);
            }
            else {
                next.set(schedulerId, updatedCalls);
            }
            return next;
        });
    }, []);
    const replaceToolCallsForScheduler = useCallback((schedulerId, updatedCalls) => {
        updateToolCallsForScheduler(schedulerId, (prevCalls) => {
            if (updatedCalls.length === 0) {
                return [];
            }
            const previousCallMap = new Map(prevCalls.map((call) => [call.request.callId, call]));
            return updatedCalls.map((call) => ({
                ...call,
                responseSubmittedToGemini: previousCallMap.get(call.request.callId)
                    ?.responseSubmittedToGemini ?? false,
            }));
        });
    }, [updateToolCallsForScheduler]);
    const updateToolCallOutput = useCallback((schedulerId, toolCallId, outputChunk) => {
        updateToolCallsForScheduler(schedulerId, (prevCalls) => {
            let updated = false;
            const nextCalls = prevCalls.map((call) => {
                if (call.request.callId !== toolCallId) {
                    return call;
                }
                if (call.status !== 'executing') {
                    return call;
                }
                updated = true;
                const executingCall = call;
                return { ...executingCall, liveOutput: outputChunk };
            });
            return updated ? nextCalls : prevCalls;
        });
        updatePendingHistoryItem(toolCallId, outputChunk);
    }, [updateToolCallsForScheduler, updatePendingHistoryItem]);
    const toolCalls = useMemo(() => Array.from(toolCallsByScheduler.values()).flat(), [toolCallsByScheduler]);
    const mainSchedulerId = useState(() => Symbol('main-scheduler'))[0];
    // The scheduler MUST be recreated when config changes because:
    // 1. config.getToolRegistry() returns different instances during initialization
    // 2. config.getApprovalMode() can change based on user settings
    // 3. The Gemini client initialization depends on having the latest config
    const scheduler = useMemo(() => new CoreToolScheduler({
        outputUpdateHandler: (toolCallId, chunk) => updateToolCallOutput(mainSchedulerId, toolCallId, chunk),
        onAllToolCallsComplete: async (completedToolCalls) => {
            if (completedToolCalls.length > 0) {
                await onComplete(mainSchedulerId, completedToolCalls, {
                    isPrimary: true,
                });
            }
            replaceToolCallsForScheduler(mainSchedulerId, []);
        },
        onToolCallsUpdate: (calls) => {
            replaceToolCallsForScheduler(mainSchedulerId, calls);
        },
        getPreferredEditor,
        config,
        onEditorClose,
        onEditorOpen,
    }), [
        config,
        getPreferredEditor,
        onEditorClose,
        mainSchedulerId,
        onComplete,
        replaceToolCallsForScheduler,
        updateToolCallOutput,
        onEditorOpen,
    ]);
    const createExternalScheduler = useCallback((args) => {
        const { schedulerConfig, onAllToolCallsComplete, outputUpdateHandler, onToolCallsUpdate, } = args;
        const schedulerId = Symbol('subagent-scheduler');
        return new CoreToolScheduler({
            config: schedulerConfig,
            outputUpdateHandler: (toolCallId, chunk) => {
                updateToolCallOutput(schedulerId, toolCallId, chunk);
                outputUpdateHandler(toolCallId, chunk);
            },
            onToolCallsUpdate: (calls) => {
                replaceToolCallsForScheduler(schedulerId, calls);
                onToolCallsUpdate?.(calls);
            },
            onAllToolCallsComplete: async (calls) => {
                if (calls.length > 0) {
                    await onComplete(schedulerId, calls, { isPrimary: false });
                    await onAllToolCallsComplete?.(calls);
                }
                replaceToolCallsForScheduler(schedulerId, []);
            },
            getPreferredEditor,
            onEditorClose,
            onEditorOpen,
        });
    }, [
        getPreferredEditor,
        onEditorClose,
        replaceToolCallsForScheduler,
        onComplete,
        updateToolCallOutput,
        onEditorOpen,
    ]);
    useEffect(() => {
        const configWithFactory = config;
        if (typeof configWithFactory.setInteractiveSubagentSchedulerFactory !==
            'function') {
            return;
        }
        configWithFactory.setInteractiveSubagentSchedulerFactory(createExternalScheduler);
        return () => {
            configWithFactory.setInteractiveSubagentSchedulerFactory?.(undefined);
        };
    }, [config, createExternalScheduler]);
    const schedule = useCallback((request, signal) => {
        const ensureAgentId = (req) => ({
            ...req,
            agentId: req.agentId ?? DEFAULT_AGENT_ID,
        });
        const normalizedRequest = Array.isArray(request)
            ? request.map(ensureAgentId)
            : ensureAgentId(request);
        scheduler.schedule(normalizedRequest, signal);
    }, [scheduler]);
    const markToolsAsSubmitted = useCallback((callIdsToMark) => {
        if (callIdsToMark.length === 0) {
            return;
        }
        setToolCallsByScheduler((prev) => {
            let changed = false;
            const next = new Map(prev);
            for (const [schedulerId, calls] of prev) {
                const updatedCalls = calls.map((call) => callIdsToMark.includes(call.request.callId)
                    ? { ...call, responseSubmittedToGemini: true }
                    : call);
                const hasChange = updatedCalls.some((call, index) => call !== calls[index]);
                if (hasChange) {
                    changed = true;
                    next.set(schedulerId, updatedCalls);
                }
            }
            return changed ? next : prev;
        });
    }, []);
    const cancelAllToolCalls = useCallback(() => {
        scheduler.cancelAll();
    }, [scheduler]);
    return [toolCalls, schedule, markToolsAsSubmitted, cancelAllToolCalls];
}
/**
 * Maps a CoreToolScheduler status to the UI's ToolCallStatus enum.
 * Memoized as a constant map for better performance.
 */
const STATUS_MAP = {
    validating: ToolCallStatus.Executing,
    awaiting_approval: ToolCallStatus.Confirming,
    executing: ToolCallStatus.Executing,
    success: ToolCallStatus.Success,
    cancelled: ToolCallStatus.Canceled,
    error: ToolCallStatus.Error,
    scheduled: ToolCallStatus.Pending,
};
function mapCoreStatusToDisplayStatus(coreStatus) {
    const mappedStatus = STATUS_MAP[coreStatus];
    if (mappedStatus !== undefined) {
        return mappedStatus;
    }
    // This should be unreachable if CoreStatus is exhaustive
    console.warn(`Unknown core status encountered: ${coreStatus}`);
    return ToolCallStatus.Error;
}
/**
 * Transforms `TrackedToolCall` objects into `HistoryItemToolGroup` objects for UI display.
 */
export function mapToDisplay(toolOrTools) {
    const toolCalls = Array.isArray(toolOrTools) ? toolOrTools : [toolOrTools];
    const groupAgentId = toolCalls
        .map((trackedCall) => {
        const responseAgentId = 'response' in trackedCall ? trackedCall.response?.agentId : undefined;
        return responseAgentId ?? trackedCall.request.agentId;
    })
        .find((agentId) => typeof agentId === 'string' && agentId.trim().length > 0) ?? DEFAULT_AGENT_ID;
    const toolDisplays = toolCalls.map((trackedCall) => {
        let displayName;
        let description;
        let renderOutputAsMarkdown = false;
        if (trackedCall.status === 'error') {
            displayName =
                trackedCall.tool === undefined
                    ? trackedCall.request.name
                    : trackedCall.tool.displayName;
            description = JSON.stringify(trackedCall.request.args);
        }
        else {
            displayName = trackedCall.tool.displayName;
            description = trackedCall.invocation.getDescription();
            renderOutputAsMarkdown = trackedCall.tool.isOutputMarkdown;
        }
        const baseDisplayProperties = {
            callId: trackedCall.request.callId,
            name: displayName,
            description,
            renderOutputAsMarkdown,
        };
        switch (trackedCall.status) {
            case 'success':
                return {
                    ...baseDisplayProperties,
                    status: mapCoreStatusToDisplayStatus(trackedCall.status),
                    resultDisplay: trackedCall.response.resultDisplay,
                    confirmationDetails: undefined,
                };
            case 'error':
                return {
                    ...baseDisplayProperties,
                    status: mapCoreStatusToDisplayStatus(trackedCall.status),
                    resultDisplay: trackedCall.response.resultDisplay,
                    confirmationDetails: undefined,
                };
            case 'cancelled':
                return {
                    ...baseDisplayProperties,
                    status: mapCoreStatusToDisplayStatus(trackedCall.status),
                    resultDisplay: trackedCall.response.resultDisplay,
                    confirmationDetails: undefined,
                };
            case 'awaiting_approval':
                return {
                    ...baseDisplayProperties,
                    status: mapCoreStatusToDisplayStatus(trackedCall.status),
                    resultDisplay: undefined,
                    confirmationDetails: trackedCall.confirmationDetails,
                };
            case 'executing':
                return {
                    ...baseDisplayProperties,
                    status: mapCoreStatusToDisplayStatus(trackedCall.status),
                    resultDisplay: trackedCall.liveOutput ?? undefined,
                    confirmationDetails: undefined,
                };
            case 'validating': // Fallthrough
            case 'scheduled':
                return {
                    ...baseDisplayProperties,
                    status: mapCoreStatusToDisplayStatus(trackedCall.status),
                    resultDisplay: undefined,
                    confirmationDetails: undefined,
                };
            default: {
                const exhaustiveCheck = trackedCall;
                return {
                    callId: exhaustiveCheck.request.callId,
                    name: 'Unknown Tool',
                    description: 'Encountered an unknown tool call state.',
                    status: ToolCallStatus.Error,
                    resultDisplay: 'Unknown tool call state',
                    confirmationDetails: undefined,
                    renderOutputAsMarkdown: false,
                };
            }
        }
    });
    return {
        type: 'tool_group',
        agentId: groupAgentId,
        tools: toolDisplays,
    };
}
//# sourceMappingURL=useReactToolScheduler.js.map