"""Generate the CC0 lift-arm example with Blender 4.x or 5.x.

Run: blender --background --factory-startup --python lift_arm.py
Writes lift-arm.glb in the working directory. The intentionally detailed
procedural finish models a texture-heavy asset; all geometry is original.
"""
import math
from pathlib import Path
from tempfile import TemporaryDirectory

import bpy
import numpy as np

bpy.ops.object.select_all(action="SELECT")
bpy.ops.object.delete()

def material(name, color):
    mat = bpy.data.materials.new(name)
    mat.diffuse_color = (*color, 1)
    return mat

def beam(name, center, size, mat):
    bpy.ops.mesh.primitive_cube_add(size=1, location=center)
    obj = bpy.context.object
    obj.name = name
    obj.dimensions = size
    bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)
    obj.data.materials.append(mat)
    return obj

def pin(name, x, radius, depth, mat):
    bpy.ops.mesh.primitive_cylinder_add(vertices=48, radius=radius, depth=depth,
        location=(x, 0, 0), rotation=(math.pi/2, 0, 0))
    obj = bpy.context.object
    obj.name = name
    obj.data.materials.append(mat)
    return obj

with TemporaryDirectory() as work:
    # Use a deterministic, fine-grained finish and keep the source embedded.
    rng = np.random.default_rng(42)
    side = 4096
    pixels = np.ones((side, side, 4), dtype=np.float32)
    for channel, base in enumerate((0.16, 0.34, 0.70)):
        pixels[:, :, channel] = base + 0.12 * rng.random((side, side), dtype=np.float32)
    finish = bpy.data.images.new("Blue powder coat", side, side, alpha=False)
    finish.pixels.foreach_set(pixels.ravel())
    finish.filepath_raw = str(Path(work) / "finish.png")
    finish.file_format = "PNG"
    finish.save()
    finish.pack()
    blue = material("Powder-coated aluminum", (0.16, 0.34, 0.70))
    blue.use_nodes = True
    tex = blue.node_tree.nodes.new("ShaderNodeTexImage")
    tex.image = finish
    shader = blue.node_tree.nodes.get("Principled BSDF")
    blue.node_tree.links.new(tex.outputs["Color"], shader.inputs["Base Color"])

    silver = material("Aluminum", (0.55, 0.59, 0.63))
    orange = material("Orange tip marker", (1.0, 0.25, 0.015))
    bpy.ops.object.empty_add(location=(0, 0, 0))
    hinge = bpy.context.object
    hinge.name = "LiftPivot"
    for obj in [beam("Arm", (0.15, 0, 0), (0.30, 0.035, 0.04), blue),
                pin("PivotPin", 0, 0.032, 0.05, silver),
                pin("TipMarker", 0.30, 0.024, 0.05, orange)]:
        obj.parent = hinge
    hinge.rotation_mode = 'XYZ'
    for frame, angle in [(1, 0), (25, -60), (49, 0)]:
        hinge.rotation_euler.y = math.radians(angle)
        hinge.keyframe_insert(data_path="rotation_euler", frame=frame)
    bpy.context.scene.frame_set(1)
    bpy.ops.export_scene.gltf(filepath=str(Path("lift-arm.glb").resolve()),
        export_format="GLB", export_animations=True)
