import { recordStage } from '../../../stages/utils.js';
import { applyReqProcessRouteSelectionWithNative } from '../../../../../../router/virtual-router/engine-selection/native-hub-pipeline-req-process-semantics.js';
import { cleanRoutingInstructionMarkersWithNative } from '../../../../../../router/virtual-router/engine-selection/native-virtual-router-routing-instructions-semantics.js';
function replaceRecordInPlace(target, source) {
    for (const key of Object.keys(target)) {
        if (!Object.prototype.hasOwnProperty.call(source, key)) {
            delete target[key];
        }
    }
    Object.assign(target, source);
}
export function runReqProcessStage2RouteSelect(options) {
    const previousModel = typeof options.request.model === 'string' ? options.request.model : undefined;
    const result = options.routerEngine.route(options.request, options.metadataInput);
    const nativeApplied = applyReqProcessRouteSelectionWithNative({
        request: options.request,
        normalizedMetadata: options.normalizedMetadata,
        target: result.target,
        routeName: result.decision.routeName,
        originalModel: previousModel
    });
    const cleanedRequest = cleanRoutingInstructionMarkersWithNative(nativeApplied.request);
    replaceRecordInPlace(options.request, cleanedRequest);
    replaceRecordInPlace(options.normalizedMetadata, nativeApplied.normalizedMetadata);
    recordStage(options.stageRecorder, 'chat_process.req.stage5.route_select', {
        target: result.target,
        decision: result.decision,
        diagnostics: result.diagnostics
    });
    return {
        target: result.target,
        decision: result.decision,
        diagnostics: result.diagnostics
    };
}
