import { applyHubOperationTableOutboundPostMap, applyHubOperationTableOutboundPreMap } from '../../../../operation-table/operation-table-runner.js';
import { recordStage } from '../../../stages/utils.js';
import { applyContextSnapshotToChatEnvelope, applyToolCallIdStyleMetadata } from './context-merge.js';
import { shouldAttachReqOutboundContextSnapshotWithNative, standardizedToChatEnvelopeWithNative } from '../../../../../../router/virtual-router/engine-selection/native-hub-pipeline-req-outbound-semantics.js';
import { validateChatEnvelopeWithNative } from '../../../../../../router/virtual-router/engine-selection/native-hub-pipeline-edge-stage-semantics.js';
export async function runReqOutboundStage1SemanticMap(options) {
    const chatEnvelope = standardizedToChatEnvelopeWithNative({
        request: options.request,
        adapterContext: options.adapterContext
    });
    applyToolCallIdStyleMetadata(chatEnvelope, options.adapterContext, options.contextSnapshot);
    const shouldAttachContextSnapshot = shouldAttachReqOutboundContextSnapshotWithNative(Boolean(options.contextSnapshot), options.contextMetadataKey);
    if (shouldAttachContextSnapshot && options.contextSnapshot && options.contextMetadataKey) {
        const snapshot = options.contextSnapshot;
        chatEnvelope.metadata[options.contextMetadataKey] = snapshot;
        applyContextSnapshotToChatEnvelope(chatEnvelope, snapshot);
    }
    validateChatEnvelopeWithNative(chatEnvelope, {
        stage: 'req_outbound',
        direction: 'request'
    });
    await applyHubOperationTableOutboundPreMap({
        protocol: options.adapterContext.providerProtocol,
        chatEnvelope,
        adapterContext: options.adapterContext
    });
    const formatEnvelope = (await options.semanticMapper.fromChat(chatEnvelope, options.adapterContext));
    applyHubOperationTableOutboundPostMap({
        chatEnvelope,
        formatEnvelope,
        adapterContext: options.adapterContext
    });
    recordStage(options.stageRecorder, 'chat_process.req.stage6.outbound.semantic_map', chatEnvelope);
    return { chatEnvelope, formatEnvelope };
}
