"""Detailed articulated button accordion. Run with Blender's background Python."""
import math
import os
import sys
import bpy
import bmesh
from mathutils import Vector

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import v4lib as v4

v4.reset()

# Materials
wine = v4.mat("oxblood_pearl_lacquer", (0.32, 0.035, 0.055), metallic=0.20, roughness=0.24, coat=0.7)
wine_dark = v4.mat("dark_wine_binding", (0.13, 0.012, 0.025), metallic=0.12, roughness=0.28, coat=0.45)
black = v4.plastic("ebony", (0.035, 0.028, 0.026), roughness=0.28)
bellows_cloth = v4.fabric("bellows_charcoal_cloth", (0.045, 0.038, 0.039))
bellows_fold = v4.fabric("bellows_fold_highlight", (0.11, 0.085, 0.078))
bellows_shadow = v4.fabric("bellows_inner_fold", (0.018, 0.016, 0.017))
ivory = v4.plastic("aged_ivory", (0.91, 0.84, 0.68), roughness=0.23)
ivory_side = v4.plastic("ivory_button_side", (0.72, 0.62, 0.43), roughness=0.31)
pearl = v4.mat("mother_of_pearl", (0.93, 0.89, 0.79), metallic=0.18, roughness=0.17, coat=0.85)
brass = v4.metal("champagne_nickel", color=(0.78, 0.66, 0.43), roughness=0.28)
steel = v4.metal("bright_steel", color=(0.73, 0.76, 0.78), roughness=0.24, brushed=True)
grille_dark = v4.mat("grille_shadow", (0.018, 0.022, 0.025), roughness=0.55)
leather = v4.mat("strap_leather", (0.095, 0.028, 0.021), roughness=0.4)
leather_pad = v4.mat("padded_oxblood_leather", (0.16, 0.045, 0.028), roughness=0.56)
thread = v4.mat("strap_stitch", (0.66, 0.48, 0.30), roughness=0.8)
rubber = v4.rubber("end_rubber", (0.045, 0.045, 0.047))

# Coordinates: X across instrument, Y front/back, Z up. Front is -Y.
root = v4.body("treble_casing")
moving = v4.body("bellows_bass")
W, D, H = 0.075, 0.205, 0.385
zc = 0.1975
front = -D / 2
back = D / 2
treble_cx, treble_inner_x, treble_outer_x = 0.1275, 0.090, 0.165
bw, bd, bh = 0.075, 0.205, 0.385
bx, bass_inner_x, bass_outer_x = -0.1475, -0.110, -0.185

# Smooth compact treble shell, layered end caps and board.
treble_shell = v4.box("treble_main_shell", (W, D, H), (treble_cx, 0, zc), bevel=0.012, material=wine, body=root)
treble_front_board = v4.box("treble_front_board", (0.023, 0.006, 0.351), (0.151, front - 0.001, zc), bevel=0.004, material=wine_dark, body=root)
treble_board_face = v4.box("treble_board_face", (0.021, 0.004, 0.342), (0.151, front - 0.006, zc), bevel=0.003, material=wine, body=root)
# A narrow, player-facing fingerboard runs along the bellows-side edge of the
# treble front. This puts each round button in clear view in the product view.
treble_face_out = Vector((0, -1, 0))
treble_board_tangent = Vector((1, 0, 0))
treble_board_x = treble_inner_x + 0.025
treble_board_center = Vector((treble_board_x, front - 0.003, zc))
treble_fingerboard = v4.box("treble_fingerboard", (0.046, 0.006, 0.338),
                            tuple(treble_board_center), bevel=0.0025, material=wine_dark, body=root)
# Bright piping follows the front board perimeter and top/bottom casing seams.
for side in (-1, 1):
    if side == -1:
        continue  # the inner edge is occupied by the angled treble fingerboard
    x = treble_cx + side * (W/2 - 0.001)
    v4.box(f"treble_binding_side_{side}", (0.0022, 0.002, 0.316), (x, front - 0.011, zc), bevel=0.0008, material=brass, body=root)
for side in (-1, 1):
    z = zc + side * 0.174
    v4.box(f"treble_binding_end_{'top' if side > 0 else 'bottom'}", (0.058, 0.002, 0.0022), (treble_cx, front - 0.008, zc + side*0.169), bevel=0.0008, material=brass, body=root)

# Treble grille: a restrained slotted vent panel beside the visible fingerboard.
gx, gw, gh = 0.151, 0.020, 0.326
gz = 0.202
v4.box("grille_shadow_panel", (gw, 0.003, gh), (gx, front - 0.009, gz), bevel=0.004, material=grille_dark, body=root)
for x in (gx - gw/2, gx + gw/2):
    v4.box("grille_frame_vertical", (0.0032, 0.004, gh + 0.006), (x, front - 0.015, gz), bevel=0.0013, material=brass, body=root)
for z in (gz - gh/2, gz + gh/2):
    v4.box("grille_frame_horizontal", (gw + 0.005, 0.004, 0.0032), (gx, front - 0.015, z), bevel=0.0013, material=brass, body=root)
for row in range(23):
    z = gz - 0.142 + row * 0.0125
    v4.box(f"grille_slot_{row}", (0.0075, 0.0012, 0.0040),
           (gx, front - 0.0112, z), bevel=0.0015, material=black, body=root)
for x in (gx-gw/2+0.002, gx+gw/2-0.002):
    v4.box(f"grille_vent_rail_{x}", (0.0012, 0.0032, gh-0.014),
           (x, front - 0.014, gz), bevel=0.00055, material=brass, body=root)

# Raised maker badge on the upper grille field.
v4.box("maker_badge", (0.018, 0.0025, 0.015), (gx, front - 0.019, 0.350), bevel=0.0025, material=brass, body=root)
v4.text("maker_mark", "B", 0.0080, loc=(gx, front - 0.021, 0.348), rot=(math.pi/2, 0, 0), material=black, body=root)

# The large outer cheek carries the main openwork sound grille. The black panel
# reads as the dark cavity behind a thin brass fret lattice, leaving real gaps
# between the rods instead of a painted-on stripe pattern.
side_x = treble_outer_x
side_grille_y, side_grille_z = 0.0, 0.205
side_grille_w, side_grille_h = 0.158, 0.302
v4.box("treble_side_grille_well", (0.003, side_grille_w, side_grille_h),
       (side_x+0.001, side_grille_y, side_grille_z), bevel=0.008, material=grille_dark, body=root)
for side_y in (-1, 1):
    y = side_y * side_grille_w/2
    v4.box(f"treble_side_grille_rail_y_{'left' if side_y < 0 else 'right'}", (0.0035,0.003,side_grille_h+0.008),
           (side_x+0.004,y,side_grille_z), bevel=0.0015, material=brass, body=root)
for z in (side_grille_z-side_grille_h/2, side_grille_z+side_grille_h/2):
    v4.box(f"treble_side_grille_rail_z{z:.3f}", (0.0035,side_grille_w+0.006,0.003),
           (side_x+0.004,0,z), bevel=0.0015, material=brass, body=root)
fret_x = side_x + 0.004
y0, y1 = -side_grille_w/2+0.008, side_grille_w/2-0.008
z0, z1 = side_grille_z-side_grille_h/2+0.010, side_grille_z+side_grille_h/2-0.010
# Slender vertical and diagonal fretwork leaves open dark diamonds between bars.
for k in range(5):
    y = y0 + k*(y1-y0)/4
    v4.rod(f"treble_fret_post_{k}", (fret_x,y,z0), (fret_x,y,z1),
           0.00105, material=brass, body=root)
for row in range(8):
    za = z0 + row*(z1-z0)/8
    zb = z0 + (row+1)*(z1-z0)/8
    for col in range(4):
        ya = y0 + col*(y1-y0)/4
        yb = y0 + (col+1)*(y1-y0)/4
        if (row+col) % 2:
            v4.rod(f"treble_fret_diag_{row}_{col}", (fret_x,ya,za), (fret_x,yb,zb),
                   0.0008, material=steel, body=root)
        else:
            v4.rod(f"treble_fret_diag_{row}_{col}", (fret_x,ya,zb), (fret_x,yb,za),
                   0.0008, material=steel, body=root)
for y in (-0.045,0.045):
    for z in (0.075,0.335):
        v4.sphere("treble_grille_rivet",0.0022,(side_x+0.005,y,z),segments=16,material=steel,body=root)
# The grille carries its maker medallion on the front-facing vent panel above;
# keep this outer fretwork field clear so every open diamond reads cleanly.

# Eight nested pleat frames telescope in a chained slide. Each moves 15 mm relative to
# its neighbour, so the eighth frame and bass casing travel 120 mm while retaining overlap.
bellows_z = 0.197
frame_count, frame_len, frame_stroke = 8, 0.044, 0.120 / 7
frame_pitch = 0.160 / (frame_count - 1)

def add_folded_sheet(name, vertices, faces, material_ids, materials, body):
    """One connected, corrugated cloth skin with visible dark valleys."""
    mesh = bpy.data.meshes.new(name + "_mesh")
    mesh.from_pydata(vertices, [], faces)
    mesh.materials.clear()
    for mat in materials:
        mesh.materials.append(mat)
    mesh.update()
    for poly, material_id in zip(mesh.polygons, material_ids):
        poly.material_index = material_id
        poly.use_smooth = False
    obj = bpy.data.objects.new(name, mesh)
    bpy.context.scene.collection.objects.link(obj)
    v4.part(obj, body)
    return obj

def add_accordion_panels(frame, name, cx, depth, height, phase=0):
    # One peak and one valley profile repeats across each telescoping bay. The
    # raised ridges catch the light; inset valleys use near-black folded cloth.
    profile = [0.0, 1.0, 0.0, -1.0, 0.0]
    xs = [cx - frame_len/2 + frame_len*i/4 for i in range(5)]
    amp = 0.0042
    zlo, zhi = bellows_z - height/2 + 0.001, bellows_z + height/2 - 0.001
    panel_mats = [bellows_cloth, bellows_fold, bellows_shadow, leather]

    for side, label in ((-1, "front"), (1, "back")):
        verts, faces, mids = [], [], []
        for x, wave in zip(xs, profile):
            y = side * (depth/2 + wave*amp)
            verts.extend(((x, y, zlo), (x, y, zhi)))
        for i in range(4):
            a, b = i*2, (i+1)*2
            if side < 0:
                faces.append((a, b, b+1, a+1))
            else:
                faces.append((a+1, b+1, b, a))
            mids.append(1 if (i + phase) % 2 == 0 else 2)
        add_folded_sheet(f"{name}_{label}_concertina", verts, faces, mids, panel_mats, frame)

    # Top and bottom folds run around the same corrugated cross-section. Two
    # narrow leather lanes are built into the top/bottom skins as bellows straps.
    ybands = [-depth/2, -0.066, -0.056, 0.056, 0.066, depth/2]
    for side, label in ((1, "top"), (-1, "bottom")):
        verts, faces, mids = [], [], []
        for x, wave in zip(xs, profile):
            z = bellows_z + side*(height/2 + wave*amp)
            for y in ybands:
                verts.append((x, y, z))
        for i in range(4):
            for j in range(len(ybands)-1):
                a = i*len(ybands)+j
                b = (i+1)*len(ybands)+j
                if side > 0:
                    faces.append((a, b, b+1, a+1))
                else:
                    faces.append((a+1, b+1, b, a))
                if j in (1, 3):
                    mids.append(3)
                else:
                    mids.append(1 if (i + phase) % 2 == 0 else 2)
        add_folded_sheet(f"{name}_{label}_concertina", verts, faces, mids, panel_mats, frame)

pleat_frames = []
previous = root
for i in range(frame_count):
    cx = 0.070 - i*frame_pitch
    depth = 0.199 - i*0.00035
    height = 0.379 - i*0.00035
    thickness = 0.0010
    frame = v4.body(f"bellows_pleat_{i:02d}")
    pleat_frames.append(frame)
    add_accordion_panels(frame, f"pleat_{i:02d}", cx, depth, height, phase=i % 2)
    # Each alternating fold receives small metal corner guards on front, back,
    # top and bottom edges. They sit into the cloth at the ridge/valley seams.
    profile = [0.0, 1.0, 0.0, -1.0, 0.0]
    amp = 0.0042
    for fold_index in (1, 3):
        fx = cx - frame_len/2 + frame_len*fold_index/4
        wave = profile[fold_index]
        for sy in (-1, 1):
            surf_y = sy*(depth/2 + wave*amp)
            for sz in (-1, 1):
                surf_z = bellows_z + sz*(height/2)
                v4.box(f"pleat_{i:02d}_corner_cap_{fold_index}_{'front' if sy < 0 else 'back'}_{'bottom' if sz < 0 else 'top'}",
                       (0.006,0.0038,0.013),
                       (fx, surf_y-sy*0.001, surf_z-sz*0.004),
                       bevel=0.0015, material=steel, body=frame)
    if i == 0:
        v4.joint("treble_bellows_mount", "fixed", previous, frame,
                 origin=(cx, 0, bellows_z), axis=(-1, 0, 0))
    else:
        v4.joint(f"pleat_slide_{i:02d}", "prismatic", previous, frame,
                 origin=(cx, 0, bellows_z), axis=(-1, 0, 0), limits=(0, frame_stroke))
    previous = frame

# Thin end hoops seal the bellows profile against both casing frames.
def bellows_end_hoop(body, name, x, depth=0.199, height=0.379):
    t = 0.003
    for sy in (-1,1):
        v4.box(name+f"_side_{'front' if sy < 0 else 'back'}", (t,t,height), (x,sy*(depth/2-t/2),bellows_z),
               bevel=0.0007, material=brass, body=body)
    for sz in (-1,1):
        v4.box(name+f"_rail_{'bottom' if sz < 0 else 'top'}", (t,depth-2*t,t), (x,0,bellows_z+sz*(height/2-t/2)),
               bevel=0.0007, material=brass, body=body)
bellows_end_hoop(root, "treble_bellows_end_frame", treble_inner_x-0.001)
bellows_end_hoop(pleat_frames[-1], "bass_bellows_end_frame", -0.108)

# Bass casing shell at the moving left end, with its own button board and corner hardware.
bass_shell = v4.box("bass_main_shell", (bw, bd, bh), (bx, 0, zc), bevel=0.012, material=wine, body=moving)
bass_front_board = v4.box("bass_front_board", (0.067, 0.006, 0.350), (bx, front - 0.001, zc), bevel=0.006, material=wine_dark, body=moving)
bass_board_face = v4.box("bass_board_face", (0.060, 0.004, 0.340), (bx, front - 0.006, zc), bevel=0.004, material=wine, body=moving)
# Bass controls occupy the outer end face, toward -X, rather than duplicating
# a treble-style field on the grille-facing front.
bass_end_board = v4.box("bass_end_board", (0.006, 0.154, 0.342),
                        (bass_outer_x - 0.003, 0.0, zc), bevel=0.0025, material=wine_dark, body=moving)
# A raised, subtly raked bezel makes the end-face control field read as a real
# fingerboard. The button pivots remain on the board's original plane.
board_rake = math.radians(3.0)
for sy in (-1, 1):
    v4.box(f"bass_board_bezel_side_{'left' if sy < 0 else 'right'}", (0.006,0.008,0.354),
           (bass_outer_x-0.007,sy*0.078,zc), rot=(0,sy*board_rake,0),
           bevel=0.003, material=brass, body=moving)
for sz in (-1, 1):
    v4.box(f"bass_board_bezel_end_{'bottom' if sz < 0 else 'top'}", (0.006,0.164,0.008),
           (bass_outer_x-0.007,0,zc+sz*0.174), rot=(0,sz*board_rake,0),
           bevel=0.003, material=brass, body=moving)
for sy in (-1,1):
    for sz in (-1,1):
        v4.sphere("bass_board_bezel_rivet",0.0024,
                   (bass_outer_x-0.010,sy*0.073,zc+sz*0.164),
                   segments=16,material=steel,body=moving)
for s in (-1, 1):
    v4.box(f"bass_binding_end_{'bottom' if s < 0 else 'top'}", (0.058, 0.002, 0.0022), (bx, front - 0.008, zc + s*0.169), bevel=0.0008, material=brass, body=moving)

# Compact strap brackets on the outer cheeks; leather shoulder bands sit on each rear shell.
for body, cx, outer_x, side, label in (
        (root, treble_cx, treble_outer_x, 1, "treble"),
        (moving, bx, bass_outer_x, -1, "bass")):
    for k, z in enumerate((0.070, 0.325)):
        plate_x = outer_x + side*0.0015
        v4.box(f"{label}_strap_bracket_{k}", (0.003,0.020,0.018),
               (plate_x, 0.0, z), bevel=0.002, material=brass, body=body)
        v4.torus(f"{label}_strap_ring_{k}", 0.0065, 0.0012,
                 loc=(outer_x + side*0.003, 0, z), rot=(0,math.pi/2,0), material=steel, body=body)
    # Adjustable leather shoulder webbing lies on the rear face and is stitched at its edges.
    strap_x = cx if label == "treble" else bass_outer_x + 0.006
    strap_width = 0.028 if label == "treble" else 0.012
    v4.box(f"{label}_shoulder_strap", (strap_width,0.006,0.260),
           (strap_x, back+0.002, zc), bevel=0.005, material=leather_pad, body=body)
    for side_x in (-1,1):
        sx = strap_x + side_x*(strap_width/2-0.003)
        for k in range(11):
            z = 0.075 + k*0.022
            v4.rod(f"{label}_strap_stitch_{side_x}_{k}", (sx,back+0.004,z),
                   (sx+side_x*0.0015,back+0.004,z+0.004), 0.00045, material=thread, body=body)
    # A pair of substantial rear shoulder anchors is fixed into the shell at
    # both strap ends, with metal eyes large enough to read in the rear view.
    for end_z in (0.070,0.325):
        for side_x in (-1,1):
            ax = strap_x + side_x*(strap_width/2-0.002)
            v4.box(f"{label}_rear_anchor_plate_{end_z}_{side_x}",
                   (0.010,0.006,0.016),(ax,back+0.003,end_z),
                   bevel=0.002,material=brass,body=body)
            v4.torus(f"{label}_rear_anchor_eye_{end_z}_{side_x}",0.0055,0.0011,
                     loc=(ax,back+0.009,end_z),rot=(math.pi/2,0,0),material=steel,body=body)

# The broad adjustable bass hand strap is mounted to the bass rear cover.
v4.box("bass_hand_strap", (0.043,0.008,0.190), (bx,back+0.004,0.205),
       bevel=0.007, material=leather, body=moving)
for zpad in (0.150,0.205,0.260):
    v4.box(f"bass_hand_strap_pad_{zpad:.3f}",(0.032,0.010,0.038),
           (bx,back+0.010,zpad),bevel=0.007,material=leather_pad,body=moving)
    for sx in (-1,1):
        xst=bx+sx*0.014
        for k in range(3):
            zst=zpad-0.012+k*0.012
            v4.rod(f"bass_hand_pad_stitch_{zpad:.3f}_{sx}_{k}",
                   (xst,back+0.016,zst),(xst-sx*0.001,zst*0+back+0.016,zst+0.003),
                   0.0004,material=thread,body=moving)
# A proper brass adjustment buckle closes the padded palm strap.
v4.box("bass_hand_buckle_tab",(0.030,0.010,0.025),(bx,back+0.010,0.284),
       bevel=0.005,material=leather_pad,body=moving)
v4.box("bass_hand_buckle_plate",(0.031,0.004,0.012),(bx,back+0.017,0.291),
       bevel=0.002,material=brass,body=moving)
v4.box("bass_hand_buckle_bar",(0.0025,0.006,0.014),(bx,back+0.019,0.291),
       bevel=0.0008,material=steel,body=moving)
for sx in (-1,1):
    v4.box(f"bass_hand_buckle_side_{sx}",(0.0025,0.006,0.014),
           (bx+sx*0.014,back+0.019,0.291),bevel=0.0008,material=steel,body=moving)
for side_x in (-1,1):
    sx = bx + side_x*0.016
    v4.rod(f"bass_hand_strap_stitch_{side_x}_a", (sx,back+0.010,0.125),
           (sx,back+0.010,0.285), 0.0004, material=thread, body=moving)

# Top and bottom bellows strap clasps sit over the shell rims, so the leather
# tabs stay physically seated when the bellows are fully extended.
for body, name, x in ((root,"treble",treble_inner_x+0.015), (moving,"bass",bass_outer_x+0.004)):
    for z, label in ((0.3875,"top"),(0.0085,"bottom")):
        v4.box(f"{name}_bellows_clasp_{label}_leather", (0.013,0.030,0.008),
               (x,-0.025,z), bevel=0.0015, material=leather, body=body)
        v4.box(f"{name}_bellows_clasp_{label}_buckle", (0.004,0.033,0.009),
               (x-0.002,-0.025,z), bevel=0.001, material=brass, body=body)

# Small brass keepers sit directly on the integrated leather lanes at the
# first and last pleat peaks, making the compression straps read as hardware.
for body, x in ((pleat_frames[0], 0.059), (pleat_frames[-1], -0.1015)):
    for sy in (-1, 1):
        v4.box(f"bellows_top_strap_keeper_{body.name}_{sy}",
               (0.012,0.019,0.0025), (x,sy*0.061,0.3919),
               bevel=0.001, material=brass, body=body)
        v4.box(f"bellows_top_strap_slot_{body.name}_{sy}",
               (0.006,0.010,0.001), (x,sy*0.061,0.3930),
               bevel=0.0004, material=black, body=body)

# Fixed collars plus separate round plungers. The board normal defines each
# button's straight inward press direction.
def make_button(name, parent_body, facepoint, radius, outward, tangent, dark_cap=False, pearl_cap=False):
    p = Vector(facepoint)
    out = Vector(outward).normalized()
    inward = -out
    tangent = Vector(tangent).normalized()
    rot = inward.to_track_quat("Z", "Y").to_euler()
    def at_out(distance):
        return tuple(p + out*distance)
    v4.cylinder(name + "_escutcheon", radius*1.18, 0.0022, at_out(0.001),
                rot=rot, segments=32, bevel=0.0, material=brass, body=parent_body)
    v4.cylinder(name + "_well", radius*0.94, 0.0015, at_out(0.0028),
                rot=rot, segments=32, bevel=0.0, material=black, body=parent_body)
    # Raised rim exposes the 4 mm stroke: the proud crown settles inside this lip.
    lip_major, lip_minor = radius*0.92, radius*0.27
    # Seat the rim into the escutcheon/well stack. On the end-facing bass
    # board this keeps the toroidal edge physically joined to its recess.
    v4.torus(name + "_raised_lip", lip_major, lip_minor, at_out(0.0027),
             rot=rot, material=brass, body=parent_body)
    b = v4.body(name)
    # Cap projects 8 mm from the face at rest; its 4 mm inward travel is visible.
    v4.rod(name + "_rocker_stem", tuple(p), at_out(0.004), radius*0.40,
           material=ivory_side, body=b)
    v4.cylinder(name + "_cap_side", radius, 0.005, at_out(0.006),
                rot=rot, segments=32, material=ivory_side, body=b)
    crown_material = leather_pad if name == "bass_air_valve" else (
        black if dark_cap else (pearl if pearl_cap else ivory))
    v4.sphere(name + "_cap_crown", radius*0.94, at_out(0.0083), segments=24,
              material=crown_material, body=b)
    v4.joint(name + "_press", "prismatic", parent_body, b,
             origin=tuple(p), axis=tuple(inward), limits=(0, 0.004))

# Treble fingerboard: three staggered rows, fourteen pearl-topped buttons per row.
treble_button_coords = []
for row in range(3):
    for k in range(14):
        z = 0.055 + k*0.022
        x = treble_board_x + (row-1)*0.012 + (0.003 if k % 2 else 0)
        radius = 0.0062
        point = Vector((x, front - 0.006, z))
        treble_button_coords.append((tuple(point), radius))
        make_button(f"treble_button_{row*14+k:02d}", root, tuple(point), radius,
                    treble_face_out, treble_board_tangent,
                    dark_cap=(k % 7 == 3 and row == 1), pearl_cap=True)

# Five low-profile register switches sit in a row above the treble button field.
for i in range(5):
    x = treble_board_x - 0.016 + i*0.008
    v4.cylinder(f"register_switch_{i}_collar", 0.0035, 0.002,
                (x, front - 0.005, 0.359), rot=(math.pi/2,0,0), bevel=0.0,
                segments=24, material=brass, body=root)
    v4.cylinder(f"register_switch_{i}_knob", 0.0026, 0.004,
                (x, front - 0.008, 0.359), rot=(math.pi/2,0,0), bevel=0.0,
                segments=24, material=black, body=root)

# Bass end board: three denser staggered rows of eight plus a larger air valve.
bass_button_coords = []
for row in range(3):
    for k in range(8):
        z = 0.095 + k*0.031
        u = (row-1)*0.038 + (0.004 if k % 2 else 0)
        radius = 0.0049
        point = Vector((bass_outer_x-0.006, u, z))
        bass_button_coords.append((tuple(point), radius))
        make_button(f"bass_button_{row*8+k:02d}", moving, tuple(point), radius,
                    (-1,0,0), (0,1,0),
                    dark_cap=(row == 1 and k in (2, 6)))
air_point = Vector((bass_outer_x-0.006, 0, 0.350))
bass_button_coords.append((tuple(air_point), 0.0065))
make_button("bass_air_valve", moving, tuple(air_point), 0.0065,
            (-1,0,0), (0,1,0), dark_cap=True)
# The air valve gets a padded leather crown and a fine brass knurled bezel
# seated around its visible rim, all moving with the valve plunger.
v4.torus("bass_air_valve_leather_bezel", 0.0062, 0.00065,
         tuple(air_point + Vector((-0.0082, 0, 0))),
         rot=(0,math.pi/2,0), material=brass, body=v4.get_body("bass_air_valve"))

# Drill aligned bores through the separate fingerboards so a fully pressed cap
# can enter the casing instead of stopping in front of a solid panel.
def cut_button_bores(target, name, coords, inward):
    # Bake the existing edge bevel before drilling; otherwise the bevel modifier
    # clamps globally at the closely spaced holes and squares off the board.
    for modifier in list(target.modifiers):
        with bpy.context.temp_override(object=target, active_object=target):
            bpy.ops.object.modifier_apply(modifier=modifier.name)
    bm = bmesh.new()
    rotation = Vector(inward).normalized().to_track_quat("Z", "Y").to_matrix()
    for point, radius in coords:
        geom = bmesh.ops.create_cone(bm, cap_ends=True, cap_tris=False, segments=24,
                                     radius1=radius*1.10, radius2=radius*1.10, depth=0.050)["verts"]
        for vert in geom:
            vert.co = Vector(point) + rotation @ vert.co
    mesh = bpy.data.meshes.new(name + "_cutters_mesh")
    bm.to_mesh(mesh)
    bm.free()
    cutter = bpy.data.objects.new(name + "_cutters", mesh)
    bpy.context.scene.collection.objects.link(cutter)
    v4.boolean(target, cutter)

# Keep the player-facing treble board solid so the narrow panel remains visible;
# escutcheons/wells provide the individual recessed visual seats. Drill the bass
# board along its open end-face axis, where that boolean preserves the panel.
for target, label, coords, x_center in (
        (bass_end_board, "bass_end_board", bass_button_coords, (1,0,0)),):
    cut_button_bores(target, label + "_button_bores", coords, inward=x_center)

# Bass casing remains attached to the terminal bellows pleat throughout the full stroke.
v4.joint("bass_casing_mount", "fixed", pleat_frames[-1], moving,
         origin=(-0.110, 0.0, bellows_z), axis=(-1, 0, 0))

# Small preview motion saved at rest by v4.save.
v4.pose({})
v4.save(os.path.join(os.getcwd(), "asset.blend"))
print("saved asset.blend")
