import { recordStage } from '../../../stages/utils.js';
import { parseRespInboundFormatEnvelopeWithNative, sanitizeFormatEnvelopeWithNative } from '../../../../../../router/virtual-router/engine-selection/native-hub-pipeline-edge-stage-semantics.js';
import { normalizeReasoningInAnthropicPayload, normalizeReasoningInChatPayload, normalizeReasoningInGeminiPayload, normalizeReasoningInResponsesPayload } from '../../../../../shared/reasoning-normalizer.js';
function resolveProtocolToken(adapterContext) {
    const candidate = typeof adapterContext.providerProtocol === 'string' && adapterContext.providerProtocol.trim().length
        ? adapterContext.providerProtocol.trim().toLowerCase()
        : '';
    if (candidate === 'openai-chat' || candidate === 'openai-responses' || candidate === 'anthropic-messages' || candidate === 'gemini-chat') {
        return candidate;
    }
    return 'openai-chat';
}
function applyReasoningNormalization(payload, protocol) {
    if (protocol === 'openai-responses') {
        normalizeReasoningInResponsesPayload(payload, {
            includeOutput: true,
            includeRequiredAction: true
        });
        return;
    }
    if (protocol === 'anthropic-messages') {
        normalizeReasoningInAnthropicPayload(payload);
        return;
    }
    if (protocol === 'gemini-chat') {
        normalizeReasoningInGeminiPayload(payload);
        return;
    }
    normalizeReasoningInChatPayload(payload);
}
export async function runRespInboundStage2FormatParse(options) {
    const protocol = resolveProtocolToken(options.adapterContext);
    applyReasoningNormalization(options.payload, protocol);
    const envelopeRaw = parseRespInboundFormatEnvelopeWithNative({
        payload: options.payload,
        protocol
    });
    const envelope = sanitizeFormatEnvelopeWithNative(envelopeRaw);
    recordStage(options.stageRecorder, 'chat_process.resp.stage2.format_parse', envelope);
    return envelope;
}
