"""Add COMPANION to the existing editable ASX library without rebuilding ALTO."""
from pathlib import Path
ROOT=Path(__file__).resolve().parent.parent
exec(compile((ROOT/'modeling/build_mezzo.py').read_text().split('DECK_START=4.12')[0],str(ROOT/'modeling/build_mezzo.py'),'exec'))
# Preserve the existing seven complete assemblies and their calibrated geometry.
with bpy.data.libraries.load(str(ROOT/'modeling/cartridge-library.blend'),link=False) as (available,loaded):
    loaded.objects=available.objects
for ob in loaded.objects:
    if ob is not None:scene.collection.objects.link(ob)
old=bpy.data.objects.get('cartridge_companion')
if old:
    for ob in list(old.children_recursive)+[old]:bpy.data.objects.remove(ob,do_unlink=True)
g=finalize_cartridge(make_companion())
objects=[g]+list(g.children_recursive)
bpy.ops.object.select_all(action='DESELECT')
for ob in objects:
    ob.select_set(True);ob.location*=.01
    if ob.type=='MESH':
        for v in ob.data.vertices:v.co*=.01
bpy.ops.export_scene.gltf(filepath=str(OUT/'cartridge-companion.glb'),export_format='GLB',use_selection=True,export_apply=True,export_yup=True,export_extras=True)
for ob in objects:
    ob.location*=100
    if ob.type=='MESH':
        for v in ob.data.vertices:v.co*=100
g.location.x=85
staged=ROOT/'modeling/cartridge-library-next.blend'
bpy.ops.wm.save_as_mainfile(filepath=str(staged))
staged.replace(ROOT/'modeling/cartridge-library.blend')
print('COMPANION_READY',flush=True)
