"""Blender 4.1+ example: blender --background --python blender-example.py -- /tmp/zaaglijst
Creates a fresh synthetic scene; run in a new Blender file. Dimensions below are metres.
"""
import bpy
import math
import os
import sys
from mathutils import Vector

args = sys.argv[sys.argv.index('--') + 1:] if '--' in sys.argv else []
out = os.path.abspath(args[0] if args else os.path.join(os.path.expanduser('~'), 'zaaglijst-example'))
os.makedirs(out, exist_ok=True)
# A separate scene protects objects in the currently open scene.
scene = bpy.data.scenes.new('Zaaglijst import example')
bpy.context.window.scene = scene
scene.unit_settings.system = 'METRIC'
scene.unit_settings.scale_length = 1

def timber(name, a, b, width, height):
    # Local X is length, local Y width, local Z height (Blender Z-up).
    delta = Vector(b) - Vector(a)
    bpy.ops.mesh.primitive_cube_add(size=1, location=(Vector(a) + Vector(b)) / 2)
    obj = bpy.context.object
    obj.name = name
    obj.dimensions = (delta.length, width, height)
    obj.rotation_mode = 'QUATERNION'
    obj.rotation_quaternion = Vector((1, 0, 0)).rotation_difference(delta)
    bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)
    obj['example_source'] = 'public synthetic Blender example'
    return obj

rail = timber('Drilled rail', (0, 0, 0.05), (1.2, 0, 0.05), .08, .1)
bpy.ops.mesh.primitive_cylinder_add(vertices=64, radius=.012, depth=.2, location=(.35, 0, .05))
cutter = bpy.context.object
modifier = rail.modifiers.new('Through drilling', 'BOOLEAN')
modifier.operation = 'DIFFERENCE'
modifier.solver = 'EXACT'
modifier.object = cutter
bpy.context.view_layer.objects.active = rail
bpy.ops.object.modifier_apply(modifier=modifier.name)
bpy.data.objects.remove(cutter, do_unlink=True)
timber('Touching rail', (1.2, 0, .05), (2.4, 0, .05), .08, .1)
timber('Rotated brace', (0, .5, 0), (.7, .5, .7), .06, .08)
for obj in scene.objects:
    obj.select_set(True)
bpy.ops.export_scene.gltf(filepath=os.path.join(out, 'blender-frame.glb'), export_format='GLB',
                          use_selection=True, use_active_scene=True, export_yup=True, export_apply=True, export_extras=True)
bpy.ops.export_scene.gltf(filepath=os.path.join(out, 'blender-frame.gltf'), export_format='GLTF_SEPARATE',
                          use_selection=True, use_active_scene=True, export_yup=True, export_apply=True, export_extras=True)
# OBJ coordinates in mm, exported Y-up. glTF above remains standards-compliant metres.
bpy.ops.wm.obj_export(filepath=os.path.join(out, 'blender-frame.obj'), export_selected_objects=True,
                      forward_axis='NEGATIVE_Z', up_axis='Y', global_scale=1000,
                      export_materials=False, export_triangulated_mesh=True)
print('Zaaglijst examples written to', out)
