"""Articulated 48 mm packing tape applicator, authored with v4lib."""
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()

# -- surface palette: moulded safety orange, satin zinc steel, rubber and clear tape --
orange = v4.painted("safety_orange_polymer", (0.78, 0.30, 0.006), roughness=0.40, coat=0.04)
orange_dark = v4.plastic("burnt_orange_trim", (0.55, 0.09, 0.018), roughness=0.34, texture=0.1)
black = v4.plastic("charcoal_nylon", (0.045, 0.052, 0.055), roughness=0.48, texture=0.18)
rubber = v4.rubber("grip_tpe", (0.025, 0.031, 0.034))
roller_rubber = v4.rubber("pressure_roller_rubber", (0.075, 0.082, 0.080))
zinc = v4.metal("satin_zinc_steel", (0.66, 0.70, 0.71), roughness=0.32)
stainless = v4.metal("brushed_stainless", (0.78, 0.80, 0.81), roughness=0.22)
black_oxide = v4.metal("black_oxide", (0.105, 0.12, 0.13), roughness=0.35, brushed=False)
core_card = v4.mat("kraft_cardboard", (0.62, 0.43, 0.24), roughness=0.76)
tape_color = v4.mat("clear_tape_amber", (0.69, 0.48, 0.23), metallic=0.0, roughness=0.27, coat=0.32)
label_white = v4.mat("roll_label_ivory", (0.91, 0.87, 0.72), roughness=0.58)
ink = v4.mat("label_ink", (0.12, 0.20, 0.22), roughness=0.6)
warning_yellow = v4.painted("warning_yellow", (0.96, 0.63, 0.035), roughness=0.3, coat=0.25)

# -- dimensional constants (metres); side view is Y-Z, the tool nose points -Y --
ROLL_C = (0.025, 0.118)
ROLL_R = 0.050
ROLL_W = 0.048
ARM_PIVOT = (0.0, -0.068, 0.084)
ROLLER_C = (0.0, -0.105, 0.020)
BLADE_PIVOT = (0.0, -0.140, 0.050)

frame = v4.body("frame")
roll = v4.body("tape_roll")
arm = v4.body("applicator_arm")
roller = v4.body("pressure_roller")
blade = v4.body("cutter_blade")

# Local X/Y of these extrusions are world Y/Z; local +Z is world +X.
YZ_ROT = (math.pi / 2, 0.0, math.pi / 2)
X_ROT = (0.0, math.pi / 2, 0.0)


def yz_extrude(name, outline, x_start, depth, material, body, bevel=0.001):
    return v4.extrude(name, outline, depth, loc=(x_start, 0, 0), rot=YZ_ROT,
                      bevel=bevel, material=material, body=body)


def capsule_yz(p0, p1, radius, n=12):
    """Closed capsule outline for 2-D points (world Y, world Z)."""
    dy, dz = p1[0] - p0[0], p1[1] - p0[1]
    a = math.atan2(dz, dy)
    pts = []
    for k in range(n + 1):
        t = a - math.pi / 2 + math.pi * k / n
        pts.append((p1[0] + radius * math.cos(t), p1[1] + radius * math.sin(t)))
    for k in range(n + 1):
        t = a + math.pi / 2 + math.pi * k / n
        pts.append((p0[0] + radius * math.cos(t), p0[1] + radius * math.sin(t)))
    return pts


def annulus_x(name, x_center, cy, cz, r_inner, r_outer, width, material, body,
              segments=96):
    """A closed annular cylinder with its axis along X."""
    bm = bmesh.new()
    x0, x1 = x_center - width / 2, x_center + width / 2
    rings = []
    for x, r in ((x0, r_inner), (x0, r_outer), (x1, r_inner), (x1, r_outer)):
        ring = []
        for i in range(segments):
            a = 2 * math.pi * i / segments
            ring.append(bm.verts.new((x, cy + r * math.cos(a), cz + r * math.sin(a))))
        rings.append(ring)
    for i in range(segments):
        j = (i + 1) % segments
        bm.faces.new((rings[0][i], rings[2][i], rings[2][j], rings[0][j]))  # bore
        bm.faces.new((rings[1][i], rings[1][j], rings[3][j], rings[3][i]))  # outside
        bm.faces.new((rings[0][i], rings[1][i], rings[1][j], rings[0][j]))  # -X face
        bm.faces.new((rings[2][i], rings[2][j], rings[3][j], rings[3][i]))  # +X face
    bmesh.ops.recalc_face_normals(bm, faces=bm.faces)
    mesh = bpy.data.meshes.new(name)
    bm.to_mesh(mesh)
    bm.free()
    obj = bpy.data.objects.new(name, mesh)
    v4._finish(obj, body, material, bevel=0.0, smooth=True)
    return obj


def ribbon_mesh(name, points_yz, width, thickness, material, body):
    """Thin solid strip running through a Y-Z centre line, across the X width."""
    verts, faces = [], []
    half = width / 2
    for i, (y, z) in enumerate(points_yz):
        prev = points_yz[max(0, i - 1)]
        nxt = points_yz[min(len(points_yz) - 1, i + 1)]
        dy, dz = nxt[0] - prev[0], nxt[1] - prev[1]
        length = max(math.hypot(dy, dz), 1e-9)
        ny, nz = -dz / length, dy / length
        for sign in (-1, 1):
            for side in (-1, 1):
                verts.append((sign * half, y + side * ny * thickness / 2,
                              z + side * nz * thickness / 2))
    # Per station: left/bottom, left/top, right/bottom, right/top.
    for i in range(len(points_yz) - 1):
        a, b = 4 * i, 4 * (i + 1)
        faces += [(a, a + 1, b + 1, b), (a + 2, b + 2, b + 3, a + 3),
                  (a, b, b + 2, a + 2), (a + 1, a + 3, b + 3, b + 1)]
    faces += [(0, 2, 3, 1), (4 * (len(points_yz) - 1),
                            4 * (len(points_yz) - 1) + 1,
                            4 * (len(points_yz) - 1) + 3,
                            4 * (len(points_yz) - 1) + 2)]
    mesh = bpy.data.meshes.new(name)
    mesh.from_pydata(verts, [], faces)
    mesh.update()
    bm = bmesh.new()
    bm.from_mesh(mesh)
    bmesh.ops.recalc_face_normals(bm, faces=bm.faces)
    bm.to_mesh(mesh)
    bm.free()
    obj = bpy.data.objects.new(name, mesh)
    v4._finish(obj, body, material, bevel=0.0, smooth=False)
    return obj


def elliptical_grip(name, p0, p1, rx, rn, material, body, stations=28, around=32):
    """Tapered ergonomic grip with an oval section across X and the handle normal."""
    p0, p1 = Vector(p0), Vector(p1)
    d = p1 - p0
    tangent = d.normalized()
    normal = Vector((0, -tangent.z, tangent.y))  # perpendicular in Y-Z
    verts, faces, centers = [], [], []
    for j in range(stations + 1):
        t = j / stations
        c = p0.lerp(p1, t)
        taper = 0.82 + 0.18 * math.sin(math.pi * t) ** 0.6
        centers.append(c)
        for k in range(around):
            a = 2 * math.pi * k / around
            verts.append((c.x + rx * taper * math.cos(a),
                          c.y + rn * taper * math.sin(a) * normal.y,
                          c.z + rn * taper * math.sin(a) * normal.z))
    for j in range(stations):
        for k in range(around):
            a, b = j * around + k, j * around + (k + 1) % around
            faces.append((a, b, b + around, a + around))
    faces.append(tuple(range(around - 1, -1, -1)))
    faces.append(tuple(stations * around + k for k in range(around)))
    mesh = bpy.data.meshes.new(name)
    mesh.from_pydata(verts, [], faces)
    mesh.update()
    bm = bmesh.new()
    bm.from_mesh(mesh)
    bmesh.ops.recalc_face_normals(bm, faces=bm.faces)
    bm.to_mesh(mesh)
    bm.free()
    obj = bpy.data.objects.new(name, mesh)
    v4._finish(obj, body, material, bevel=0.0, smooth=True)
    return centers, tangent, normal


def saw_blade_mesh(name, xhalf, y_front, thickness, z_top, z_base, z_tip,
                   pitch, material, body):
    """Extruded blade plate with a single continuous fine triangular saw edge."""
    outline = [(-xhalf, z_top), (xhalf, z_top), (xhalf, z_base)]
    n = int((2 * xhalf) / pitch)
    step = 2 * xhalf / n
    # Walk from the right heel toward the left, forming the tooth edge.
    for i in range(n - 1, -1, -1):
        right = -xhalf + (i + 1) * step
        left = -xhalf + i * step
        tipx = left + step * 0.68
        outline.extend([(tipx, z_tip), (left, z_base)])
    outline.append((-xhalf, z_top))
    verts = [(x, y_front, z) for x, z in outline] + [
        (x, y_front + thickness, z) for x, z in outline]
    count = len(outline)
    faces = [tuple(range(count)), tuple(range(count, 2 * count))]
    for i in range(count):
        j = (i + 1) % count
        faces.append((i, j, count + j, count + i))
    mesh = bpy.data.meshes.new(name)
    mesh.from_pydata(verts, [], faces)
    mesh.update()
    bm = bmesh.new()
    bm.from_mesh(mesh)
    bmesh.ops.recalc_face_normals(bm, faces=bm.faces)
    bm.to_mesh(mesh)
    bm.free()
    obj = bpy.data.objects.new(name, mesh)
    v4._finish(obj, body, material, bevel=0.00025, segments=2, smooth=False)
    return obj

# ---------------------------------------------------------------- frame: paired open cheeks / grip / fixed hub / cutter bracket

cheek_outline = [
    (-0.150, 0.044), (-0.145, 0.071), (-0.125, 0.091), (-0.096, 0.108),
    (-0.079, 0.135), (-0.057, 0.164), (-0.029, 0.176), (0.050, 0.176),
    (0.083, 0.157), (0.096, 0.127), (0.098, 0.083), (0.112, 0.049),
    (0.124, 0.025), (0.122, 0.012), (0.109, 0.008), (0.080, 0.009),
    (0.055, 0.047), (0.020, 0.050), (-0.017, 0.034), (-0.047, 0.012),
    (-0.104, 0.008), (-0.132, 0.015), (-0.143, 0.027),
]
plate_t = 0.003
for side, x0 in (("left", -0.0275), ("right", 0.0245)):
    cheek = yz_extrude(f"{side}_orange_side_cheek", cheek_outline, x0, plate_t,
                       orange, frame, bevel=0.0016)
    # Large round window exposes the full tape roll; the handle relief is a compact obround.
    round_cut = v4.cylinder(f"{side}_roll_window_tool", 0.0535, 0.007,
                            (x0 + plate_t / 2, ROLL_C[0], ROLL_C[1]), rot=X_ROT,
                            segments=96, bevel=0, material=None)
    v4.boolean(cheek, round_cut)
    grip_cut = yz_extrude(f"{side}_grip_window_tool",
                          capsule_yz((0.088, 0.093), (0.105, 0.027), 0.0105, 16),
                          x0 - 0.001, plate_t + 0.002, black, None, bevel=0)
    v4.boolean(cheek, grip_cut)

# Narrow dark seam panels and fasteners on the orange cheek faces.
for side_sign in (-1, 1):
    xface = side_sign * 0.0275
    plaque = v4.box(f"{('L' if side_sign < 0 else 'R')}_model_badge",
                    (0.0016, 0.046, 0.013),
                    (side_sign * 0.0283, -0.052, 0.064), bevel=0.0013,
                    material=black, body=frame)
    if side_sign > 0:
        v4.text("packpro_badge", "PACKPRO", 0.0052,
                loc=(0.02915, -0.052, 0.066), rot=YZ_ROT,
                extrude_depth=0.00025, material=label_white, body=frame, on=plaque)
        v4.text("size_badge", "48 mm", 0.0035,
                loc=(0.02915, -0.052, 0.0615), rot=YZ_ROT,
                extrude_depth=0.0002, material=warning_yellow, body=frame, on=plaque)
    for j, (y, z) in enumerate(((-0.132, 0.023), (-0.057, 0.159), (0.078, 0.151), (0.119, 0.038))):
        v4.cylinder(f"cheek_rivet_{side_sign}_{j}", 0.0022, 0.0018,
                    (side_sign * 0.0284, y, z), rot=X_ROT, segments=24,
                    bevel=0.0002, material=black_oxide, body=frame)

# Fixed hub: steel axle, sliding-core clearance and two exact-contact elastomer drag bearings.
v4.cylinder("fixed_core_hub_shaft", 0.011, 0.066, (0, ROLL_C[0], ROLL_C[1]),
            rot=X_ROT, segments=64, bevel=0.0006, material=zinc, body=frame)
for side in (-1, 1):
    annulus_x(f"core_drag_bearing_{side}", side * 0.0125, ROLL_C[0], ROLL_C[1],
              0.011, 0.014, 0.0030, rubber, frame, segments=64)
    # fixed outer spindle collar, clear of the printed roll face
    v4.cylinder(f"spindle_collar_{side}", 0.0122, 0.0032,
                (side * 0.0285, ROLL_C[0], ROLL_C[1]), rot=X_ROT,
                segments=48, bevel=0.0005, material=black_oxide, body=frame)
    v4.torus(f"spindle_cap_rim_{side}", 0.0106, 0.00075,
             (side * 0.0303, ROLL_C[0], ROLL_C[1]), rot=X_ROT,
             material=stainless, body=frame)
    # short radial ribs on the thumb cap, moulded into the fixed side of the hub
    for k in range(12):
        a = 2 * math.pi * k / 12
        y = ROLL_C[0] + 0.0114 * math.cos(a)
        z = ROLL_C[1] + 0.0114 * math.sin(a)
        v4.box(f"hub_grip_lobe_{side}_{k}", (0.0025, 0.0011, 0.0023),
               (side * 0.0298, y, z), rot=(a, 0, 0), bevel=0.0003,
               material=black_oxide, body=frame)

# Three narrow stationary webs on each side carry the central spindle back to the
# side cheek's circular window rim. They sit in the 3 mm side clearance, outside the
# rotating roll faces, and make the hub a genuinely supported assembly.
for side in (-1, 1):
    for k, angle in enumerate((math.radians(42), math.radians(162), math.radians(282))):
        r0, r1 = 0.0115, 0.0550
        p0 = (side * 0.0269,
              ROLL_C[0] + r0 * math.cos(angle),
              ROLL_C[1] + r0 * math.sin(angle))
        p1 = (side * 0.0269,
              ROLL_C[0] + r1 * math.cos(angle),
              ROLL_C[1] + r1 * math.sin(angle))
        v4.rod(f"hub_support_spoke_{side}_{k}", p0, p1, 0.00125,
               material=zinc, body=frame, bevel=0.0002)

# The side cheeks are tied together at the core hub and grip; the nose crossmember
# supports the cutter without crossing the moving roll.
v4.box("front_nose_crossmember", (0.052, 0.010, 0.009), (0, -0.118, 0.070),
       bevel=0.0015, material=zinc, body=frame)

# Ergonomic overmould, with a pinched waist and seven raised transverse ribs.
grip_centers, grip_tangent, grip_normal = elliptical_grip(
    "one_piece_textured_handle_grip", (0, 0.080, 0.096), (0, 0.096, 0.022),
    0.022, 0.0116, rubber, frame)
# Cross-bolts at the cap ends connect the grip to the two side cheeks.
for i, (y, z) in enumerate(((0.080, 0.096), (0.096, 0.022))):
    v4.rod(f"grip_end_cross_pin_{i}", (-0.027, y, z), (0.027, y, z), 0.0032,
           material=black_oxide, body=frame, bevel=0.0004)
# Moulded raised grip bands follow the oval section.
for idx in range(1, 8):
    t = idx / 8
    c = Vector((0, 0.080, 0.096)).lerp(Vector((0, 0.096, 0.022)), t)
    taper = 0.82 + 0.18 * math.sin(math.pi * t) ** 0.6
    pts = []
    for k in range(49):
        a = 2 * math.pi * k / 48
        pts.append((c.x + 0.022 * taper * math.cos(a),
                    c.y + 0.0116 * taper * math.sin(a) * grip_normal.y,
                    c.z + 0.0116 * taper * math.sin(a) * grip_normal.z))
    v4.tube(f"grip_moulded_rib_{idx}", pts, 0.00065,
            material=black, body=frame, resolution=4, cyclic=True)
# Angular side rails inside the cheek outline highlight the load-bearing stamped frame.
for side_sign in (-1, 1):
    v4.rod(f"frame_handle_spine_{side_sign}",
           (side_sign * 0.024, -0.103, 0.021),
           (side_sign * 0.024, -0.074, 0.079), 0.0030,
           material=zinc, body=frame, bevel=0.00035)

# Hub and arm pivot marks: pin, hollow arm bushings, torsion spring coils and their tails.
ARM_Y, ARM_Z = ARM_PIVOT[1], ARM_PIVOT[2]
v4.cylinder("fixed_arm_pivot_pin", 0.0025, 0.070, ARM_PIVOT,
            rot=X_ROT, segments=40, bevel=0.0003, material=black_oxide, body=frame)
for side in (-1, 1):
    x = side * 0.033
    # A visible torsion coil around each pivot; the spring is a visual element, not a force solver.
    points = []
    turns = 3.25
    count = 100
    for i in range(count + 1):
        u = i / count
        a = 2 * math.pi * turns * u
        points.append((x - 0.003 + 0.006 * u,
                       ARM_Y + 0.0060 * math.cos(a),
                       ARM_Z + 0.0060 * math.sin(a)))
    v4.tube(f"arm_torsion_spring_{side}", points, 0.00072,
            material=stainless, body=arm, resolution=4)
    v4.rod(f"spring_fixed_tail_{side}",
           (x, ARM_Y + 0.0057, ARM_Z - 0.001),
           (x, ARM_Y + 0.012, ARM_Z - 0.010), 0.0008,
           material=stainless, body=arm, bevel=0)
    # Frame-side pivot boss and external pin head.
    v4.cylinder(f"arm_pivot_boss_{side}", 0.007, 0.002,
                (side * 0.0285, ARM_Y, ARM_Z), rot=X_ROT,
                segments=48, bevel=0.0004, material=orange_dark, body=frame)
    v4.cylinder(f"arm_pivot_pin_head_{side}", 0.0035, 0.0018,
                (side * 0.0298, ARM_Y, ARM_Z), rot=X_ROT,
                segments=32, bevel=0.0003, material=stainless, body=frame)

# Cutter bed and its two outboard hinge ears.
v4.box("cutter_bracket_bed", (0.056, 0.012, 0.012),
       (0, -0.132, 0.051), bevel=0.001, material=zinc, body=frame)
for side in (-1, 1):
    ear = yz_extrude(f"cutter_bracket_ear_{side}",
                     [(-0.140, 0.048), (-0.132, 0.062), (-0.121, 0.061),
                      (-0.125, 0.046), (-0.137, 0.042)],
                     side * 0.026, 0.004, zinc, frame, bevel=0.0006)
    v4.cylinder(f"cutter_ear_bearing_{side}", 0.0041, 0.004,
                (side * 0.032, BLADE_PIVOT[1], BLADE_PIVOT[2]), rot=X_ROT,
                segments=32, bevel=0.0004, material=black_oxide, body=frame)
# Yellow warning pad on the non-cutting top of the bed.
warning_pad = v4.box("cutter_warning_pad", (0.036, 0.006, 0.004), (0, -0.129, 0.060),
                     bevel=0.001, material=warning_yellow, body=frame)
v4.text("blade_caution_mark", "CAUTION", 0.0028,
        loc=(0, -0.129, 0.06205), rot=(0, 0, 0),
        extrude_depth=0.0002, material=black_oxide, body=frame, on=warning_pad)

# A static thin web shows the real feed path from the bottom of the roll, under the
# applicator tread, and forward to the saw. It is fixed because this authoring format has
# no deforming flexible-body or payout constraint.
feed_path = [
    (0.025, 0.0678), (0.007, 0.0677), (-0.012, 0.0638),
    (-0.032, 0.0540), (-0.051, 0.0410), (-0.069, 0.0240),
    (-0.081, 0.0140), (-0.090, 0.0100), (-0.095, 0.0050),
    (-0.100, 0.0032), (-0.105, 0.0028), (-0.110, 0.0032),
    (-0.115, 0.0050), (-0.120, 0.0090), (-0.126, 0.0155),
    (-0.134, 0.0230), (-0.142, 0.0280), (-0.147, 0.0290),
]
ribbon_mesh("stationary_clear_tape_feed_web", feed_path, 0.048, 0.00012,
            tape_color, frame)

# A small directional arrow moulded into the cheek just above the grip badge.
arrow = yz_extrude("feed_direction_arrow", [(-0.071, 0.082), (-0.062, 0.086),
                    (-0.066, 0.081), (-0.061, 0.078)],
                   0.0302, 0.0007, warning_yellow, frame, bevel=0.0002)

# ---------------------------------------------------------------- rotating tape roll
# Outer wound tape and kraft core are annuli, so the fixed hub has a genuine through-bore.
annulus_x("48mm_clear_adhesive_roll", 0.0, ROLL_C[0], ROLL_C[1],
          0.019, ROLL_R, ROLL_W, tape_color, roll, segments=128)
annulus_x("kraft_cardboard_core", 0.0, ROLL_C[0], ROLL_C[1],
          0.014, 0.019, ROLL_W, core_card, roll, segments=96)
# Subtle winding ridges at the outside circumference and the two paper edges.
for i, x in enumerate((-0.020, -0.015, -0.010, -0.005, 0.0, 0.005, 0.010, 0.015, 0.020)):
    v4.torus(f"wound_tape_edge_{i}", 0.04975, 0.00022,
             (x, ROLL_C[0], ROLL_C[1]), rot=X_ROT,
             material=label_white if i in (0, 8) else tape_color, body=roll)
for side in (-1, 1):
    # Annular printed paper label leaves a real hole around the stationary spindle.
    label_face = annulus_x(f"roll_side_label_{side}", side * 0.02412,
                           ROLL_C[0], ROLL_C[1], 0.0160, 0.0330, 0.00024,
                           label_white, roll, segments=96)
    # Fine dark rings and small registration ticks make the end label read as printed stock.
    v4.torus(f"label_print_ring_{side}", 0.0307, 0.00032,
             (side * 0.02429, ROLL_C[0], ROLL_C[1]), rot=X_ROT,
             material=ink, body=roll)
    for k in range(20):
        a = 2 * math.pi * k / 20
        r = 0.0284
        y, z = ROLL_C[0] + r * math.cos(a), ROLL_C[1] + r * math.sin(a)
        # Small dark radial dashes laid across the annular paper face.
        v4.box(f"label_tick_{side}_{k}", (0.00030, 0.0018, 0.00055),
               (side * 0.02429, y, z), rot=(a, 0, 0), bevel=0.0001,
               material=ink, body=roll)
    if side > 0:
        v4.text("roll_label_brand", "PACKING TAPE", 0.0031,
                loc=(0.02425, ROLL_C[0], ROLL_C[1] + 0.022), rot=YZ_ROT,
                extrude_depth=0.00018, material=ink, body=roll, on=label_face)

# ---------------------------------------------------------------- pivoting applicator arm and free-running roller
v4.joint("roll_spindle", "continuous", frame, roll,
         origin=(0, ROLL_C[0], ROLL_C[1]), axis=(1, 0, 0))
v4.joint("arm_hinge", "revolute", frame, arm,
         origin=ARM_PIVOT, axis=(1, 0, 0),
         limits=(-math.radians(13.8), math.radians(18.3)))

# Tapered formed-steel links straddle the roll web; hollow barrels ride on frame pins.
link_outline = [
    (-0.062, 0.090), (-0.068, 0.093), (-0.074, 0.091),
    (-0.111, 0.029), (-0.114, 0.020), (-0.110, 0.013),
    (-0.101, 0.016), (-0.063, 0.080), (-0.060, 0.086),
]
for side, x0 in ((-1, -0.035), (1, 0.031)):
    yz_extrude(f"arm_stamped_link_{side}", link_outline, x0, 0.004,
               black_oxide, arm, bevel=0.0010)
    annulus_x(f"arm_pivot_bushing_{side}", side * 0.033,
              ARM_PIVOT[1], ARM_PIVOT[2], 0.0026, 0.0056, 0.008,
              zinc, arm, segments=48)
    v4.cylinder(f"arm_joint_cover_{side}", 0.0062, 0.0012,
                (side * 0.0368, ARM_PIVOT[1], ARM_PIVOT[2]), rot=X_ROT,
                segments=40, bevel=0.0004, material=orange, body=arm)
# Axle remains part of the moving yoke, while the roller turns around it.
v4.cylinder("arm_roller_axle", 0.0025, 0.070, ROLLER_C, rot=X_ROT,
            segments=40, bevel=0.00025, material=zinc, body=arm)

# Free-running roller assembly: rubber tire, inner metal race and end hubs all rotate together.
annulus_x("treaded_pressure_tire", 0.0, ROLLER_C[1], ROLLER_C[2],
          0.0100, 0.0170, 0.050, roller_rubber, roller, segments=96)
annulus_x("roller_aluminium_race", 0.0, ROLLER_C[1], ROLLER_C[2],
          0.0030, 0.0100, 0.050, zinc, roller, segments=64)
for side in (-1, 1):
    annulus_x(f"roller_end_hub_{side}", side * 0.025,
              ROLLER_C[1], ROLLER_C[2], 0.0030, 0.0096, 0.002,
              orange_dark, roller, segments=56)
    v4.torus(f"roller_end_lip_{side}", 0.0087, 0.00065,
             (side * 0.02615, ROLLER_C[1], ROLLER_C[2]), rot=X_ROT,
             material=stainless, body=roller)
for i, x in enumerate((-0.019, -0.014, -0.009, -0.004, 0.004, 0.009, 0.014, 0.019)):
    v4.torus(f"roller_tread_groove_{i}", 0.01675, 0.00055,
             (x, ROLLER_C[1], ROLLER_C[2]), rot=X_ROT,
             material=black, body=roller)
v4.joint("roller_axle", "continuous", arm, roller,
         origin=ROLLER_C, axis=(1, 0, 0))

# ---------------------------------------------------------------- hinged serrated cutter and its bracket
v4.cylinder("fixed_cutter_hinge_pin", 0.0018, 0.065, BLADE_PIVOT,
            rot=X_ROT, segments=32, bevel=0.0002, material=black_oxide, body=frame)
# Annular sleeve provides clearance around the fixed hinge pin.
annulus_x("blade_hinge_sleeve", 0.0, BLADE_PIVOT[1], BLADE_PIVOT[2],
          0.0020, 0.0038, 0.058, black_oxide, blade, segments=48)
saw_blade_mesh("full_width_serrated_stainless_edge", 0.027,
               -0.146, 0.0018, 0.047, 0.034, 0.028, 0.00235,
               stainless, blade)
# Ground cutting bevel is represented by a narrow darker stripe at the tooth roots.
v4.box("blade_spine_polished_strip", (0.052, 0.0007, 0.0020),
       (0, -0.1462, 0.044), bevel=0.00035,
       material=zinc, body=blade)
# Small hinge collars are part of the moving blade assembly and remain clear of the bracket ears.
for side in (-1, 1):
    v4.cylinder(f"blade_hinge_end_cap_{side}", 0.0041, 0.002,
                (side * 0.030, BLADE_PIVOT[1], BLADE_PIVOT[2]), rot=X_ROT,
                segments=32, bevel=0.0003, material=stainless, body=blade)
v4.joint("blade_hinge", "revolute", frame, blade,
         origin=BLADE_PIVOT, axis=(1, 0, 0),
         limits=(-math.radians(11.5), math.radians(21.8)))

# Tool silhouette data for review; joints save at the neutral working pose.
bpy.context.scene["asset_name"] = "Handheld 48 mm packing tape applicator"
bpy.context.scene["nominal_dimensions_m"] = [0.274, 0.173, 0.074]
bpy.context.scene["mechanism_note"] = "Tape web and torsion spring force are visual only; roll, arm, roller and blade are articulated."

v4.save(os.path.join(os.getcwd(), "asset.blend"))
print("saved asset.blend")
