import { runResponsesOpenAIRequestCodecWithNative, runResponsesOpenAIResponseCodecWithNative } from '../../router/virtual-router/engine-selection/native-compat-action-semantics.js';
export class ResponsesOpenAIConversionCodec {
    dependencies;
    id = 'responses-openai';
    initialized = false;
    ctxMap = new Map();
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    constructor(dependencies) {
        this.dependencies = dependencies;
    }
    async initialize() {
        this.initialized = true;
    }
    async convertRequest(payload, _profile, context) {
        await this.ensureInit();
        const requestId = context.requestId ?? `req_${Date.now()}`;
        const native = runResponsesOpenAIRequestCodecWithNative((payload ?? {}), { requestId });
        const request = native.request && typeof native.request === 'object' && !Array.isArray(native.request)
            ? native.request
            : {};
        const capturedContext = native.context && typeof native.context === 'object' && !Array.isArray(native.context)
            ? {
                ...native.context,
                requestId,
                endpoint: context.endpoint ?? context.entryEndpoint,
                entryEndpoint: context.entryEndpoint,
                targetProtocol: _profile.outgoingProtocol,
                metadata: native.context &&
                    typeof native.context.metadata === 'object' &&
                    !Array.isArray(native.context.metadata)
                    ? native.context.metadata
                    : (context.metadata ?? {})
            }
            : {
                requestId,
                endpoint: context.endpoint ?? context.entryEndpoint,
                entryEndpoint: context.entryEndpoint,
                targetProtocol: _profile.outgoingProtocol,
                metadata: context.metadata ?? {}
            };
        this.ctxMap.set(requestId, capturedContext);
        return request;
    }
    async convertResponse(payload, _profile, context) {
        await this.ensureInit();
        const requestId = context.requestId;
        const stored = requestId ? this.ctxMap.get(requestId) : undefined;
        if (requestId) {
            this.ctxMap.delete(requestId);
        }
        const nativeContext = {
            ...(stored ?? {}),
            requestId: requestId ?? stored?.requestId,
            endpoint: context.endpoint ?? stored?.endpoint,
            entryEndpoint: context.entryEndpoint ?? context.endpoint ?? stored?.entryEndpoint,
            metadata: (stored?.metadata && typeof stored.metadata === 'object' && !Array.isArray(stored.metadata)
                ? stored.metadata
                : context.metadata) ?? {}
        };
        return runResponsesOpenAIResponseCodecWithNative((payload ?? {}), nativeContext);
    }
    async ensureInit() {
        if (!this.initialized)
            await this.initialize();
    }
}
