"""Run in Blender background mode; creates and links a temporary collection."""
import bpy
import os
import tempfile

with tempfile.TemporaryDirectory(prefix="blender-link-example-") as folder:
    library_path = os.path.join(folder, "character-library.blend")
    bpy.ops.wm.read_factory_settings(use_empty=True)
    character = bpy.data.collections.new("Character")
    bpy.context.scene.collection.children.link(character)
    mesh = bpy.data.meshes.new("HeadMesh")
    obj = bpy.data.objects.new("Head", mesh)
    character.objects.link(obj)
    bpy.ops.wm.save_as_mainfile(filepath=library_path)

    bpy.ops.wm.read_factory_settings(use_empty=True)
    with bpy.data.libraries.load(library_path, link=True) as (source, target):
        assert "Character" in source.collections
        target.collections = ["Character"]
    linked = target.collections[0]
    assert linked is not None and linked.library is not None
    bpy.context.scene.collection.children.link(linked)
    assert "Head" in linked.objects
    print("PASS: linked Character collection and its Head object from the temporary library")
