import { buildAdapterContextFromPipeline } from '../../../hooks/adapter-context.js';
import { standardizedToChatEnvelopeWithNative } from '../../../../../router/virtual-router/engine-selection/native-hub-pipeline-req-outbound-semantics.js';
import { mapOpenaiChatFromChatWithNative } from '../../../../../router/virtual-router/engine-selection/native-hub-pipeline-semantic-mappers.js';
import { runOpenAIResponseCodecWithNative } from '../../../../../router/virtual-router/engine-selection/native-compat-action-semantics.js';
export const DEFAULT_OPENAI_ENDPOINT = '/v1/chat/completions';
export const OPENAI_PROTOCOL = 'openai-chat';
function ensureJsonObject(value, stage) {
    if (!value || typeof value !== 'object' || Array.isArray(value)) {
        throw new Error(`OpenAI chat helper requires JSON object payload at ${stage}`);
    }
    return value;
}
export async function convertStandardizedToOpenAIChat(standardized, context, options) {
    const adapterContext = buildAdapterContextFromPipeline(context, {
        defaultEntryEndpoint: options?.defaultEndpoint ?? DEFAULT_OPENAI_ENDPOINT,
        overrideProtocol: OPENAI_PROTOCOL
    });
    const chatEnvelope = standardizedToChatEnvelopeWithNative({
        request: standardized,
        adapterContext: adapterContext
    });
    const formatEnvelope = mapOpenaiChatFromChatWithNative(chatEnvelope, adapterContext);
    return ensureJsonObject(formatEnvelope.payload, 'openai_request_build');
}
export async function canonicalizeOpenAIChatResponse(payload, context, options) {
    return ensureJsonObject(runOpenAIResponseCodecWithNative(payload, {
        requestId: context.requestId ?? `req_${Date.now()}`,
        endpoint: context.entryEndpoint ?? context.endpoint ?? options?.defaultEndpoint ?? DEFAULT_OPENAI_ENDPOINT,
        stream: context.stream === true,
        reasoningMode: context.metadata?.reasoningMode,
        profile: options?.profile ?? OPENAI_PROTOCOL,
        idPrefixBase: 'reasoning_choice'
    }), 'openai_response_filters');
}
