import { createToolCallIdTransformerWithNative, normalizeResponsesToolCallIdsWithNative, normalizeFunctionCallIdWithNative, normalizeFunctionCallOutputIdWithNative, normalizeResponsesCallIdWithNative, resolveToolCallIdStyleWithNative, stripInternalToolingMetadataWithNative } from '../../router/virtual-router/engine-selection/native-shared-conversion-semantics.js';
import { sanitizeResponsesFunctionNameWithNative } from '../../router/virtual-router/engine-selection/native-hub-pipeline-resp-semantics.js';
function assertResponsesToolUtilsNativeAvailable() {
    if (typeof createToolCallIdTransformerWithNative !== 'function' ||
        typeof normalizeResponsesToolCallIdsWithNative !== 'function' ||
        typeof normalizeFunctionCallIdWithNative !== 'function' ||
        typeof normalizeFunctionCallOutputIdWithNative !== 'function' ||
        typeof normalizeResponsesCallIdWithNative !== 'function' ||
        typeof resolveToolCallIdStyleWithNative !== 'function' ||
        typeof stripInternalToolingMetadataWithNative !== 'function' ||
        typeof sanitizeResponsesFunctionNameWithNative !== 'function') {
        throw new Error('[responses-tool-utils] native bindings unavailable');
    }
}
function replaceMutableRecord(target, next) {
    for (const key of Object.keys(target)) {
        delete target[key];
    }
    Object.assign(target, next);
}
export function createToolCallIdTransformer(style) {
    assertResponsesToolUtilsNativeAvailable();
    if (style !== 'fc') {
        return null;
    }
    const state = createToolCallIdTransformerWithNative(style);
    return {
        normalizeCallId(raw) {
            return normalizeResponsesCallIdWithNative({
                callId: typeof raw === 'string' && raw.trim().length ? raw.trim() : undefined,
                fallback: transformCounter(state, 'call')
            });
        },
        normalizeItemId(raw, callId) {
            return normalizeFunctionCallIdWithNative({
                callId: typeof raw === 'string' && raw.trim().length ? raw.trim() : callId,
                fallback: transformCounter(state, 'item')
            });
        },
        normalizeOutputId(callId, raw) {
            return normalizeFunctionCallOutputIdWithNative({
                callId,
                fallback: typeof raw === 'string' && raw.trim().length ? raw.trim() : transformCounter(state, 'tool')
            });
        }
    };
}
function transformCounter(state, prefix) {
    const current = typeof state.__counter === 'number' ? state.__counter : 0;
    const next = current + 1;
    state.__counter = next;
    return `${prefix}_${next}`;
}
export function normalizeResponsesToolCallIds(payload) {
    assertResponsesToolUtilsNativeAvailable();
    if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
        return;
    }
    const normalized = normalizeResponsesToolCallIdsWithNative(payload);
    if (normalized && typeof normalized === 'object' && !Array.isArray(normalized)) {
        replaceMutableRecord(payload, normalized);
    }
}
export function resolveToolCallIdStyle(metadata) {
    assertResponsesToolUtilsNativeAvailable();
    const style = resolveToolCallIdStyleWithNative(metadata ?? null);
    return style === 'preserve' ? 'preserve' : 'fc';
}
export function stripInternalToolingMetadata(metadata) {
    assertResponsesToolUtilsNativeAvailable();
    if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata))
        return;
    const normalized = stripInternalToolingMetadataWithNative(metadata);
    if (normalized && typeof normalized === 'object' && !Array.isArray(normalized)) {
        replaceMutableRecord(metadata, normalized);
    }
}
export function sanitizeResponsesFunctionName(rawName) {
    assertResponsesToolUtilsNativeAvailable();
    return sanitizeResponsesFunctionNameWithNative(rawName);
}
export function enforceToolCallIdStyle(input, transformer) {
    assertResponsesToolUtilsNativeAvailable();
    for (const entry of input) {
        if (!entry || typeof entry !== 'object')
            continue;
        const type = typeof entry.type === 'string' ? entry.type.toLowerCase() : '';
        if (type === 'function_call') {
            const normalizedCallId = transformer.normalizeCallId(entry.call_id ?? entry.id);
            entry.call_id = normalizedCallId;
            entry.id = transformer.normalizeItemId(entry.id ?? normalizedCallId, normalizedCallId);
            continue;
        }
        if (type === 'function_call_output' || type === 'tool_result' || type === 'tool_message') {
            const normalizedCallId = transformer.normalizeCallId(entry.call_id ?? entry.tool_call_id ?? entry.id);
            entry.call_id = normalizedCallId;
            // Keep tool_call_id for providers that expect it (e.g., Qwen)
            entry.tool_call_id = normalizedCallId;
            entry.id = transformer.normalizeOutputId(normalizedCallId, entry.id);
        }
    }
}
