import { recordStage } from '../../../stages/utils.js';
import { sanitizeReqInboundFormatEnvelopeWithNative } from '../../../../../../router/virtual-router/engine-selection/native-hub-pipeline-req-inbound-semantics.js';
import { parseReqInboundFormatEnvelopeWithNative } 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(rawRequest, protocol) {
    if (protocol === 'openai-responses') {
        normalizeReasoningInResponsesPayload(rawRequest, {
            includeInput: true,
            includeInstructions: true
        });
        return;
    }
    if (protocol === 'anthropic-messages') {
        normalizeReasoningInAnthropicPayload(rawRequest);
        return;
    }
    if (protocol === 'gemini-chat') {
        normalizeReasoningInGeminiPayload(rawRequest);
        return;
    }
    normalizeReasoningInChatPayload(rawRequest);
}
export async function runReqInboundStage1FormatParse(options) {
    const protocol = resolveProtocolToken(options.adapterContext);
    applyReasoningNormalization(options.rawRequest, protocol);
    const envelopeRaw = parseReqInboundFormatEnvelopeWithNative({
        rawRequest: options.rawRequest,
        protocol
    });
    const envelope = sanitizeReqInboundFormatEnvelopeWithNative(envelopeRaw);
    recordStage(options.stageRecorder, 'chat_process.req.stage1.format_parse', envelope);
    return envelope;
}
