Relocate all instanced collections to a linked library

I have a file that contains over 2K of collections. Same file also contains a scene that is made of instanced collections.

What I would like to do is split the file to one that only contains collections with real objects and another file that has them linked.

The way to do this manually would be simply deleting a collection that is instanced and linking it from a separate file into the instance. But I don’t want to do this manually.

Is there a way to do this via script, or is there some funcion I’m not aware of? Something like find missing but instead for missing files I would force it to look for same instanced collections within another file?