import { readRuntimeMetadata } from '../../runtime-metadata.js';
import { buildWebSearchToolAppendOperations } from './chat-process-web-search-tool-schema.js';
import { planChatWebSearchOperationsWithNative } from '../../../router/virtual-router/engine-selection/native-chat-process-servertool-orchestration-semantics.js';
export function buildWebSearchOperations(request, metadata, precomputedPlan) {
    const rt = (readRuntimeMetadata(metadata) ?? {});
    const rawConfig = rt?.webSearch;
    if (!rawConfig || !Array.isArray(rawConfig.engines) || rawConfig.engines.length === 0) {
        return [];
    }
    const plan = precomputedPlan ??
        planChatWebSearchOperationsWithNative(request, rt);
    if (!plan.shouldInject || !plan.selectedEngineIndexes.length) {
        return [];
    }
    const selectedEngines = selectEnginesByIndexes(rawConfig.engines, plan.selectedEngineIndexes);
    if (!selectedEngines.length) {
        return [];
    }
    return buildWebSearchToolAppendOperations(selectedEngines);
}
function selectEnginesByIndexes(engines, indexes) {
    return indexes
        .map((value) => (typeof value === 'number' && Number.isFinite(value) ? Math.floor(value) : -1))
        .filter((value) => value >= 0 && value < engines.length)
        .map((value) => engines[value]);
}
