const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
/**
 * Compat for Claude models routed via antigravity on gemini-chat.
 *
 * Anthropic requires tools[*].custom.input_schema to be valid JSON Schema draft 2020-12.
 * We currently send OpenAI-style parameters which may not fully conform, causing upstream
 * invalid_request_error on tools.N.custom.input_schema.
 *
 * For safety, when we detect the antigravity.*.claude-* path over gemini-chat,
 * we aggressively simplify Gemini functionDeclarations[*].parameters to a minimal
 * but valid object schema, letting RouteCodex govern tool semantics while keeping
 * Anthropic's schema validator happy.
 */
export function applyClaudeThinkingToolSchemaCompat(payload, adapterContext) {
    const modelRaw = payload.model;
    const modelId = typeof modelRaw === 'string' ? modelRaw.trim() : '';
    // Only apply on Claude models.
    // Upstream Anthropic enforces strict JSON Schema 2020-12 on custom.input_schema for these models.
    if (!modelId.startsWith('claude-')) {
        return payload;
    }
    const root = structuredClone(payload);
    // Support both shapes:
    // - Provider envelope: { model, request: { tools, ... } }
    // - Gemini mapper request: { model, tools, ... }
    const requestNode = isRecord(root.request)
        ? root.request
        : root;
    const toolsRaw = requestNode.tools;
    if (!Array.isArray(toolsRaw)) {
        return root;
    }
    const nextTools = [];
    for (const entry of toolsRaw) {
        if (!isRecord(entry)) {
            nextTools.push(entry);
            continue;
        }
        const decls = Array.isArray(entry.functionDeclarations)
            ? entry.functionDeclarations
            : undefined;
        if (!decls || !decls.length) {
            // Non functionDeclarations-based tools (e.g. googleSearch) are left as-is.
            nextTools.push(entry);
            continue;
        }
        const nextDecls = [];
        for (const fn of decls) {
            if (!isRecord(fn)) {
                nextDecls.push(fn);
                continue;
            }
            const fnCopy = { ...fn };
            // Replace parameters with a minimal, always-valid object schema.
            fnCopy.parameters = {
                type: 'object',
                properties: {},
                additionalProperties: true
            };
            // Drop strict flag to avoid upstream schema incompatibilities.
            if (Object.prototype.hasOwnProperty.call(fnCopy, 'strict')) {
                delete fnCopy.strict;
            }
            nextDecls.push(fnCopy);
        }
        nextTools.push({
            functionDeclarations: nextDecls
        });
    }
    requestNode.tools = nextTools;
    return root;
}
