import { runReqOutboundStage3CompatWithNative, runRespInboundStage3CompatWithNative } from '../../../../router/virtual-router/engine-selection/native-hub-pipeline-req-outbound-semantics.js';
import { buildNativeReqOutboundCompatAdapterContext } from './native-adapter-context.js';
const RATE_LIMIT_ERROR = 'ERR_COMPAT_RATE_LIMIT_DETECTED';
function normalizeProfileId(profileId) {
    if (typeof profileId !== 'string') {
        return undefined;
    }
    const trimmed = profileId.trim();
    return trimmed.length ? trimmed : undefined;
}
function toCompatResult(payload, appliedProfile) {
    if (typeof appliedProfile === 'string' && appliedProfile.trim().length) {
        return { payload, appliedProfile: appliedProfile.trim() };
    }
    return { payload };
}
export function runRequestCompatPipeline(profileId, payload, options) {
    const explicitProfile = normalizeProfileId(profileId);
    if (!explicitProfile) {
        return { payload };
    }
    const nativeCompat = runReqOutboundStage3CompatWithNative({
        payload,
        explicitProfile,
        adapterContext: buildNativeReqOutboundCompatAdapterContext(options?.adapterContext)
    });
    return toCompatResult(nativeCompat.payload, nativeCompat.appliedProfile);
}
export function runResponseCompatPipeline(profileId, payload, options) {
    const explicitProfile = normalizeProfileId(profileId);
    if (!explicitProfile) {
        return { payload };
    }
    const nativeCompat = runRespInboundStage3CompatWithNative({
        payload,
        explicitProfile,
        adapterContext: buildNativeReqOutboundCompatAdapterContext(options?.adapterContext)
    });
    if (nativeCompat.nativeApplied === true && nativeCompat.rateLimitDetected === true) {
        const err = new Error('Provider returned rate limit notice');
        err.code = RATE_LIMIT_ERROR;
        err.statusCode = 429;
        throw err;
    }
    return toCompatResult(nativeCompat.payload, nativeCompat.appliedProfile);
}
