import { buildProcessedRequestFromChatResponse } from '../../../../response/chat-response-utils.js';
import { recordStage } from '../../../stages/utils.js';
import { finalizeRespProcessChatResponseWithNative } from '../../../../../../router/virtual-router/engine-selection/native-chat-process-governance-semantics.js';
import { normalizeReasoningInChatPayload } from '../../../../../shared/reasoning-normalizer.js';
export async function runRespProcessStage2Finalize(options) {
    const endpoint = (options.entryEndpoint || '').toLowerCase();
    const wantsAnthropicReasoning = endpoint.includes('/v1/messages');
    const shouldNormalize = (options.reasoningMode && options.reasoningMode !== 'keep') || wantsAnthropicReasoning;
    if (shouldNormalize) {
        try {
            normalizeReasoningInChatPayload(options.payload);
        }
        catch {
            // best-effort inline reasoning extraction
        }
    }
    const finalized = (await finalizeRespProcessChatResponseWithNative({
        payload: options.payload,
        stream: options.wantsStream,
        reasoningMode: options.reasoningMode,
        endpoint: options.entryEndpoint,
        requestId: options.requestId
    }));
    const processedRequest = buildProcessedRequestFromChatResponse(finalized, {
        stream: options.wantsStream
    });
    recordStage(options.stageRecorder, 'chat_process.resp.stage8.finalize', {
        model: finalized.model,
        stream: options.wantsStream
    });
    return { finalizedPayload: finalized, processedRequest };
}
