import { standardizedToChatEnvelope } from '../../../../hub/standardized-bridge.js';
import { buildAdapterContextFromPipeline } from '../../../hooks/adapter-context.js';
import { ChatFormatAdapter } from '../../../../hub/format-adapters/chat-format-adapter.js';
import { ChatSemanticMapper } from '../../../../hub/semantic-mappers/chat-mapper.js';
import { FilterEngine, ResponseToolTextCanonicalizeFilter, ResponseToolArgumentsStringifyFilter, ResponseFinishInvariantsFilter } from '../../../../../filters/index.js';
import { normalizeChatResponseReasoningTools } from '../../../../shared/reasoning-tool-normalizer.js';
export const DEFAULT_OPENAI_ENDPOINT = '/v1/chat/completions';
export const OPENAI_PROTOCOL = 'openai-chat';
const sharedChatFormatAdapter = new ChatFormatAdapter();
const sharedChatSemanticMapper = new ChatSemanticMapper();
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 = standardizedToChatEnvelope(standardized, { adapterContext });
    const formatEnvelope = await sharedChatSemanticMapper.fromChat(chatEnvelope, adapterContext);
    const payload = await sharedChatFormatAdapter.buildRequest(formatEnvelope, adapterContext);
    return ensureJsonObject(payload, 'openai_request_build');
}
export async function canonicalizeOpenAIChatResponse(payload, context, options) {
    const dto = {
        data: payload,
        metadata: {
            requestId: context.requestId ?? `req_${Date.now()}`,
            pipelineId: context.metadata?.pipelineId ?? 'conversion-router',
            processingTime: 0,
            stages: []
        }
    };
    const filterContext = {
        requestId: dto.metadata.requestId,
        model: typeof payload.model === 'string' ? payload.model : undefined,
        endpoint: context.entryEndpoint ?? context.endpoint ?? options?.defaultEndpoint ?? DEFAULT_OPENAI_ENDPOINT,
        profile: options?.profile ?? OPENAI_PROTOCOL,
        debug: { emit: () => { } }
    };
    const engine = new FilterEngine();
    engine.registerFilter(new ResponseToolTextCanonicalizeFilter());
    engine.registerFilter(new ResponseToolArgumentsStringifyFilter());
    engine.registerFilter(new ResponseFinishInvariantsFilter());
    const stage1 = await engine.run('response_pre', dto.data, filterContext);
    const stage2 = await engine.run('response_map', stage1, filterContext);
    const stage3 = await engine.run('response_post', stage2, filterContext);
    const normalized = ensureJsonObject(stage3, 'openai_response_filters');
    try {
        normalizeChatResponseReasoningTools(normalized, { idPrefixBase: 'reasoning_choice' });
    }
    catch {
        // reasoning normalization best-effort
    }
    return normalized;
}
