import { buildNativeReqOutboundCompatAdapterContext } from '../../hub/pipeline/compat/native-adapter-context.js';
import { runReqOutboundStage3CompatWithNative } from '../../../router/virtual-router/engine-selection/native-hub-pipeline-req-outbound-semantics.js';
const PROFILE = 'chat:deepseek-web';
const DEFAULT_PROVIDER_PROTOCOL = 'openai-chat';
const DEFAULT_ENTRY_ENDPOINT = '/v1/chat/completions';
const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
const readBoolean = (value) => {
    if (typeof value === 'boolean') {
        return value;
    }
    if (typeof value === 'string') {
        const normalized = value.trim().toLowerCase();
        if (['true', '1', 'yes', 'on'].includes(normalized)) {
            return true;
        }
        if (['false', '0', 'no', 'off'].includes(normalized)) {
            return false;
        }
    }
    return undefined;
};
const readToolProtocol = (value) => {
    if (typeof value !== 'string') {
        return undefined;
    }
    const normalized = value.trim().toLowerCase();
    return normalized === 'native' || normalized === 'text' ? normalized : undefined;
};
function resolveDeepseekNode(adapterContext) {
    const nativeContext = buildNativeReqOutboundCompatAdapterContext(adapterContext);
    const baseNode = isRecord(nativeContext.deepseek) ? nativeContext.deepseek : {};
    const baseProtocol = readToolProtocol(baseNode.toolProtocol);
    const baseFallback = readBoolean(baseNode.textToolFallback);
    const protocol = baseProtocol ?? (baseFallback === undefined ? undefined : baseFallback ? 'text' : 'native');
    return {
        ...baseNode,
        strictToolRequired: readBoolean(baseNode.strictToolRequired) ?? true,
        textToolFallback: protocol ? protocol === 'text' : baseFallback ?? true,
        ...(protocol ? { toolProtocol: protocol } : {})
    };
}
function buildCompatInput(payload, adapterContext) {
    const nativeContext = buildNativeReqOutboundCompatAdapterContext(adapterContext);
    const normalizedContext = {
        ...nativeContext,
        compatibilityProfile: PROFILE,
        providerProtocol: nativeContext.providerProtocol ?? adapterContext?.providerProtocol ?? DEFAULT_PROVIDER_PROTOCOL,
        entryEndpoint: nativeContext.entryEndpoint ?? adapterContext?.entryEndpoint ?? DEFAULT_ENTRY_ENDPOINT,
        deepseek: resolveDeepseekNode(adapterContext)
    };
    return {
        payload,
        adapterContext: normalizedContext,
        explicitProfile: PROFILE
    };
}
export function applyDeepSeekWebRequestTransform(payload, adapterContext) {
    if (!payload || typeof payload !== 'object') {
        return payload;
    }
    return runReqOutboundStage3CompatWithNative(buildCompatInput(payload, adapterContext)).payload;
}
