const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
export function applyRequestRules(payload, config) {
    if (!config) {
        return payload;
    }
    const cloned = { ...payload };
    const toolRule = config.tools?.['function'];
    if (toolRule?.removeKeys && Array.isArray(cloned.tools)) {
        for (const toolEntry of cloned.tools) {
            if (!isRecord(toolEntry)) {
                continue;
            }
            const fnNode = toolEntry.function;
            if (!isRecord(fnNode)) {
                continue;
            }
            for (const key of toolRule.removeKeys) {
                delete fnNode[key];
            }
        }
    }
    const assistantRule = config.messages?.assistantToolCalls?.['function'];
    if (Array.isArray(cloned.messages) && assistantRule?.removeKeys) {
        for (const message of cloned.messages) {
            if (!isRecord(message) || !Array.isArray(message.tool_calls)) {
                continue;
            }
            for (const callEntry of message.tool_calls) {
                if (!isRecord(callEntry)) {
                    continue;
                }
                const fnNode = callEntry.function;
                if (!isRecord(fnNode)) {
                    continue;
                }
                for (const key of assistantRule.removeKeys) {
                    delete fnNode[key];
                }
            }
        }
    }
    if (Array.isArray(config.topLevel?.conditional)) {
        for (const rule of config.topLevel.conditional) {
            if (!rule)
                continue;
            if (rule.when?.tools === 'empty') {
                if (Array.isArray(cloned.tools) && cloned.tools.length === 0) {
                    for (const field of rule.remove || []) {
                        delete cloned[field];
                    }
                }
            }
            if (rule.when?.tools === 'present') {
                if (Array.isArray(cloned.tools) && cloned.tools.length > 0) {
                    for (const field of rule.remove || []) {
                        delete cloned[field];
                    }
                }
            }
        }
    }
    return cloned;
}
