export function isRenderableFabricObject(object: any): boolean {
  return Boolean(object && typeof object.render === 'function');
}

export function addFabricObjectAtIndex(canvas: any, object: any, index: number): boolean {
  if (!canvas || !isRenderableFabricObject(object)) return false;

  try {
    canvas.add?.(object);
  } catch {
    return false;
  }

  const normalizedIndex = Math.max(0, Number.isFinite(index) ? Math.trunc(index) : 0);
  try {
    if (typeof canvas.moveObjectTo === 'function') {
      canvas.moveObjectTo(object, normalizedIndex);
      return true;
    }
    if (typeof canvas.moveTo === 'function') {
      canvas.moveTo(object, normalizedIndex);
      return true;
    }

    const objects = canvas._objects;
    if (Array.isArray(objects)) {
      const currentIndex = objects.indexOf(object);
      if (currentIndex >= 0) objects.splice(currentIndex, 1);
      objects.splice(Math.min(normalizedIndex, objects.length), 0, object);
    }
  } catch {
    // The object is already on the canvas. A failed optional reorder must not
    // replace it with Fabric's version-dependent insertAt arguments.
  }

  return true;
}
