import { isAgentReadOnly } from "../../services/agentService";
import { calculateTotalTokens, groupConsecutiveMessages, } from "../agentMessageGrouping";
import { convertAgentMessagesToAiFormat } from "../agentMessageConversion";
import { extractTodosFromMessages } from "../agentTodoExtraction";
export function selectReadOnly(state) {
    return state.loadStatus === "loading" ? true : isAgentReadOnly(state.agent);
}
export function selectAgentCostLimit(state) {
    try {
        const value = state.agent?.costLimit;
        const parsed = value != null ? Number(value) : 0;
        return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;
    }
    catch {
        return undefined;
    }
}
export function selectEffectiveModelName(state, input = {}) {
    const fromContextWindow = state.contextWindowStatus?.model?.trim();
    if (fromContextWindow)
        return fromContextWindow;
    const fromAgent = state.agent?.model?.trim();
    if (fromAgent)
        return fromAgent;
    const models = input.activeProfile?.models || [];
    const selectedModelName = input.selectedModelId
        ? models.find((model) => model.id === input.selectedModelId)?.name?.trim()
        : undefined;
    if (selectedModelName)
        return selectedModelName;
    const defaultModelName = input.activeProfile?.defaultModelId
        ? models
            .find((model) => model.id === input.activeProfile?.defaultModelId)
            ?.name?.trim()
        : undefined;
    if (defaultModelName)
        return defaultModelName;
    return models[0]?.name?.trim() || undefined;
}
export function selectIsWatchdogActive(input) {
    return (!input.isStopGuardActive &&
        (input.isExecuting ||
            input.isAgentThinking ||
            input.isSubmitting ||
            input.isConnecting ||
            input.isWaitingForResponse ||
            input.hasActiveStreaming));
}
export function selectShouldShowThinkingDots(input) {
    if (input.sessionCostLimitExceeded)
        return false;
    if (input.activeInlineDialog)
        return false;
    if (input.allPendingApprovalsCount > 0)
        return false;
    if (input.showInitialThinkingSplash)
        return false;
    if (input.isExecuting) {
        for (let i = input.messages.length - 1; i >= 0; i -= 1) {
            const message = input.messages[i];
            if (!message)
                continue;
            if (message.role === "tool")
                continue;
            if (message.messageType === "heartbeat")
                continue;
            if (message.role === "assistant") {
                return false;
            }
            break;
        }
    }
    const hasActiveStreamingMessage = input.messages.some((message) => !message.isCompleted && message.role === "assistant");
    if (hasActiveStreamingMessage)
        return false;
    return (input.isAgentThinking ||
        input.isSubmitting ||
        input.isConnecting ||
        input.isWaitingForResponse);
}
export function selectHasSpawnedAgents(state) {
    const childAgents = state.metadata?.childAgents;
    if (!Array.isArray(childAgents) || childAgents.length === 0) {
        return false;
    }
    return childAgents.some((agent) => agent != null && typeof agent === "object" && agent.agentId);
}
export function selectHasTodoContent(state) {
    if (selectMetadataHasTodos(state.metadata)) {
        return true;
    }
    if (extractTodosFromMessages(state.transcript).length > 0) {
        return true;
    }
    return state.transcript.some((message) => message.role === "assistant" &&
        !message.isCompleted &&
        (message.content || "").includes("todo_list"));
}
export function selectIsExecuting(state) {
    const status = String(state.agent?.status ?? state.run.status ?? "");
    const hasSettledToNonExecutingStatus = status === "idle" ||
        status === "completed" ||
        status === "error" ||
        status === "closed" ||
        status === "waitingForApproval" ||
        status === "waitingForInput" ||
        status === "costLimitReached";
    const hasActiveStreaming = state.transcript.some((message) => !message.isCompleted && message.messageType === "streaming");
    return (!state.run.stopGuardActive &&
        (state.run.isSubmitting ||
            state.run.isConnecting ||
            (!hasSettledToNonExecutingStatus &&
                (state.run.isWaitingForResponse || hasActiveStreaming))));
}
function selectMetadataHasTodos(metadata) {
    try {
        const todoList = metadata?.additionalData?.todoList;
        if (todoList?.items && Array.isArray(todoList.items)) {
            return todoList.items.some((item) => item?.title || item?.text || item?.label || item?.task);
        }
    }
    catch {
        return false;
    }
    return false;
}
export function selectPendingApprovals(state) {
    return selectPendingApprovalsFromMessages(state.transcript);
}
export function selectTotalTokens(state) {
    return selectTotalTokensFromMessages(state.transcript, Number(state.agent?.totalImageCost) || 0);
}
export function selectTotalTokensFromMessages(messages, fallbackImageCost = 0) {
    const totals = calculateTotalTokens(messages);
    return {
        ...totals,
        imageCost: totals.imageCost || fallbackImageCost,
    };
}
export function selectMessageStats(state) {
    return selectMessageStatsFromMessages(state.transcript);
}
export function selectMessageStatsFromMessages(messages) {
    const groups = groupConsecutiveMessages(messages);
    let assistantMessageCount = 0;
    let messagesWithToolCallsCount = 0;
    let totalToolCallCount = 0;
    let incompleteToolCallCount = 0;
    for (const message of messages) {
        if (message.role === "assistant") {
            assistantMessageCount += 1;
        }
        const toolCalls = message.toolCalls || [];
        if (toolCalls.length > 0) {
            messagesWithToolCallsCount += 1;
        }
        totalToolCallCount += toolCalls.length;
        incompleteToolCallCount += toolCalls.filter((toolCall) => !toolCall.isCompleted).length;
    }
    const assistantGroups = groups.filter((group) => group.type === "assistant-group");
    const assistantGroupsWithRenderableToolCalls = assistantGroups.filter((group) => {
        const convertedMessages = convertAgentMessagesToAiFormat(group.messages);
        return convertedMessages.some((message) => (message.tool_calls?.length || 0) > 0);
    }).length;
    return {
        assistantMessageCount,
        assistantGroupCount: assistantGroups.length,
        assistantGroupsWithRenderableToolCalls,
        messagesWithToolCallsCount,
        totalToolCallCount,
        incompleteToolCallCount,
    };
}
export function selectLatestSummaryAssistantGroup(messages, hideSummaryMessages) {
    if (hideSummaryMessages)
        return null;
    const groups = groupConsecutiveMessages(messages);
    for (let groupIndex = groups.length - 1; groupIndex >= 0; groupIndex -= 1) {
        const group = groups[groupIndex];
        if (!group || group.type !== "assistant-group")
            continue;
        const filteredMessages = group.messages.filter((message) => {
            const content = message.content || "";
            return (!content.startsWith("\u26a0\ufe0f") || !content.includes("Cost limit"));
        });
        if (filteredMessages.length === 0)
            continue;
        return {
            messages: filteredMessages,
            isLastGroup: groupIndex === groups.length - 1,
        };
    }
    return null;
}
export function selectPendingApprovalsFromMessages(messages) {
    const pending = [];
    const seenToolCallIds = new Set();
    for (let i = messages.length - 1; i >= 0; i--) {
        const message = messages[i];
        if (!message)
            continue;
        for (const toolCall of message.toolCalls ?? []) {
            if (toolCall.toolCallId && seenToolCallIds.has(toolCall.toolCallId)) {
                continue;
            }
            if (toolCall.toolCallId)
                seenToolCallIds.add(toolCall.toolCallId);
            const requiresApproval = toolCall.requiresApproval;
            const functionName = toolCall.functionName || "";
            const hasApprovalMetadata = !!requiresApproval && !toolCall.isCompleted;
            const hasPendingSuffix = functionName.includes("(pending approval)");
            const isApproved = functionName.includes("(approved)");
            const isRejected = functionName.includes("(rejected)");
            if ((!hasApprovalMetadata && !hasPendingSuffix) ||
                isApproved ||
                isRejected ||
                toolCall.isCompleted) {
                continue;
            }
            pending.push({
                messageId: toolCall.messageId || message.id,
                dbMessageId: toolCall.dbMessageId,
                toolCallId: toolCall.toolCallId,
                functionName: toolCall.functionName,
                summary: requiresApproval?.summary ?? "",
                riskLevel: requiresApproval?.riskLevel,
            });
        }
    }
    return pending.reverse();
}
//# sourceMappingURL=agentSessionSelectors.js.map