import { normalizeFunctionCallId, normalizeFunctionCallOutputId, normalizeResponsesCallId } from '../../bridge-id-utils.js';
function isRecord(value) {
    return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
}
function normalizeToCallId(raw, fallback) {
    const rawStr = typeof raw === 'string' ? raw.trim() : '';
    return normalizeResponsesCallId({ callId: rawStr || undefined, fallback });
}
/**
 * LM Studio compat:
 * Some LM Studio OpenAI-Responses endpoints accept tool-call items but are picky about ids:
 * - `call_id` should remain `call_*` (used to link tool outputs)
 * - `id` for `function_call` / `function_call_output` should be `fc_*` (OpenAI Responses convention)
 *
 * We apply this in compat (profile: chat:lmstudio) to keep provider layer transport-only.
 */
export function enforceLmstudioResponsesFcToolCallIds(payload) {
    try {
        if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
            return payload;
        }
        const root = structuredClone(payload);
        const input = root.input;
        if (!Array.isArray(input) || input.length === 0) {
            return root;
        }
        let callCounter = 0;
        for (const item of input) {
            if (!isRecord(item))
                continue;
            const type = typeof item.type === 'string' ? item.type.trim().toLowerCase() : '';
            if (type !== 'function_call' && type !== 'function_call_output') {
                continue;
            }
            const rawCallId = (item.call_id ?? item.tool_call_id ?? item.id);
            const callId = normalizeToCallId(rawCallId, `call_${++callCounter}`);
            item.call_id = callId;
            if (type === 'function_call') {
                const normalizedItemId = normalizeFunctionCallId({
                    callId,
                    fallback: `fc_${callId}`
                });
                item.id = normalizedItemId;
                continue;
            }
            // function_call_output
            const normalizedOutputId = normalizeFunctionCallOutputId({
                callId,
                fallback: typeof item.id === 'string' && item.id.trim().length ? item.id.trim() : `fc_tool_${callCounter}`
            });
            item.id = normalizedOutputId;
        }
        root.input = input;
        return root;
    }
    catch {
        return payload;
    }
}
