"""Articulated tabletop crank marble lift; run with Blender's Python interpreter."""
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: warm wood, painted steelwork, and bright toy marbles.
beech = v4.wood("honey_beech", light=(0.76, 0.58, 0.36), dark=(0.45, 0.27, 0.13), grain_scale=6)
walnut = v4.wood("walnut_frame", light=(0.43, 0.27, 0.15), dark=(0.22, 0.11, 0.055), grain_scale=7)
endgrain = v4.wood("beech_endgrain", light=(0.66, 0.45, 0.25), dark=(0.37, 0.21, 0.10), grain_scale=10)
red = v4.painted("lift_red_enamel", (0.76, 0.12, 0.075), roughness=0.26, coat=0.65)
yellow_enamel = v4.painted("wheel_index_yellow", (0.96, 0.64, 0.075), roughness=0.25, coat=0.65)
scoop_interior = v4.painted("scoop_inner_burgundy", (0.39, 0.045, 0.035), roughness=0.32, coat=0.45)
teal = v4.painted("track_turquoise_enamel", (0.035, 0.35, 0.38), roughness=0.28, coat=0.6)
teal_light = v4.painted("track_edge_turquoise", (0.11, 0.54, 0.53), roughness=0.24, coat=0.65)
aqua_guard = v4.painted("ascending_guide_aqua_enamel", (0.22, 0.58, 0.60), roughness=0.24, coat=0.55)
navy = v4.painted("gear_deep_blue", (0.07, 0.19, 0.27), roughness=0.3, coat=0.45)
brass = v4.metal("satin_brass", color=(0.78, 0.54, 0.22), roughness=0.3)
steel = v4.metal("brushed_steel", color=(0.66, 0.70, 0.72), roughness=0.32)
dark_steel = v4.metal("gunmetal", color=(0.21, 0.24, 0.25), roughness=0.37, brushed=False)
rubber = v4.rubber("foot_rubber", (0.055, 0.06, 0.06))
ivory = v4.mat("ivory_print", (0.93, 0.82, 0.59), roughness=0.53)
marble_orange = v4.plastic("orange_marble", (0.94, 0.23, 0.045), roughness=0.18, texture=0.04)
marble_yellow = v4.plastic("yellow_marble", (0.97, 0.69, 0.08), roughness=0.18, texture=0.04)
marble_blue = v4.plastic("blue_marble", (0.08, 0.39, 0.88), roughness=0.18, texture=0.04)

# Machine dimensions in metres. Front is -Y; Z=0 is the tabletop.
BASE_W, BASE_D = 0.46, 0.30
WHEEL_X, WHEEL_Y, WHEEL_Z = -0.075, -0.025, 0.205
CRANK_X, SHAFT_Z = -0.1534, 0.205
PINION_R, DRIVE_R = 0.028, 0.0504
GEAR_Y = -0.132
TRACK_W = 0.040
TRACK_H = 0.014
TRACK_T = 0.004

frame = v4.body("frame")
crank = v4.body("crank")
lift = v4.body("lift_wheel")
gate = v4.body("lever_gate")


def extruded_polygon(name, points_xz, y_center, depth, material, body, bevel=0.0006):
    """Extrude a simple XZ outline along Y and attach it to a rigid body."""
    n = len(points_xz)
    verts = []
    for y in (y_center - depth / 2, y_center + depth / 2):
        verts.extend((x, y, z) for x, z in points_xz)
    faces = [tuple(range(n - 1, -1, -1)), tuple(range(n, 2 * n))]
    for i in range(n):
        j = (i + 1) % n
        faces.append((i, j, n + j, n + i))
    mesh = bpy.data.meshes.new(name + "_mesh")
    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._link(obj)
    v4.assign(obj, material)
    if bevel > 0:
        mod = obj.modifiers.new("soft machined edges", "BEVEL")
        mod.width = bevel
        mod.segments = 2
        mod.limit_method = "ANGLE"
    wn = obj.modifiers.new("weighted normals", "WEIGHTED_NORMAL")
    wn.keep_sharp = True
    v4.part(obj, body)
    return obj


def gear_outline(teeth, pitch_radius, module, phase):
    """A clean, shallow tooth profile for an exposed toy spur gear."""
    tooth_pitch = 2 * math.pi / teeth
    root = pitch_radius - 1.25 * module
    tip = pitch_radius + module
    pts = []
    for i in range(teeth):
        c = phase + i * tooth_pitch
        profile = [
            (root, c - 0.50 * tooth_pitch),
            (root, c - 0.34 * tooth_pitch),
            (tip, c - 0.23 * tooth_pitch),
            (tip, c + 0.23 * tooth_pitch),
            (root, c + 0.34 * tooth_pitch),
            (root, c + 0.50 * tooth_pitch),
        ]
        for radius, ang in profile[:-1]:
            pts.append((radius * math.cos(ang), radius * math.sin(ang)))
    return pts


def add_gear(name, cx, cz, y, teeth, pitch_radius, module, phase, material, body):
    outline = gear_outline(teeth, pitch_radius, module, phase)
    return extruded_polygon(name, [(cx + x, cz + z) for x, z in outline], y, 0.012, material, body, 0.00035)


def add_track(points, open_ends=True):
    """A one-piece U-channel swept along a smooth polyline."""
    def catmull(p0, p1, p2, p3, t):
        t2, t3 = t * t, t * t * t
        return tuple(0.5 * ((2 * p1[k]) + (-p0[k] + p2[k]) * t +
                            (2 * p0[k] - 5 * p1[k] + 4 * p2[k] - p3[k]) * t2 +
                            (-p0[k] + 3 * p1[k] - 3 * p2[k] + p3[k]) * t3)
                     for k in range(3))

    centers = []
    for i in range(len(points) - 1):
        p0 = points[max(0, i - 1)]
        p1, p2 = points[i], points[i + 1]
        p3 = points[min(len(points) - 1, i + 2)]
        for s in range(5):
            centers.append(catmull(p0, p1, p2, p3, s / 5.0))
    centers.append(points[-1])

    half = TRACK_W / 2
    wall = 0.004
    profile = [(-half, 0), (half, 0), (half, TRACK_H), (half - wall, TRACK_H),
               (half - wall, wall), (-half + wall, wall), (-half + wall, TRACK_H), (-half, TRACK_H)]
    verts = []
    for i, p in enumerate(centers):
        prev = centers[max(0, i - 1)]
        nxt = centers[min(len(centers) - 1, i + 1)]
        dx, dy = nxt[0] - prev[0], nxt[1] - prev[1]
        ll = math.hypot(dx, dy)
        nx, ny = -dy / ll, dx / ll
        for lateral, zoff in profile:
            verts.append((p[0] + nx * lateral, p[1] + ny * lateral, p[2] + zoff))
    faces = []
    nprof = len(profile)
    # Swept side walls along the whole channel.
    for i in range(len(centers) - 1):
        a, b = i * nprof, (i + 1) * nprof
        for k in range(nprof):
            kn = (k + 1) % nprof
            faces.append((a + k, a + kn, b + kn, b + k))
    if not open_ends:
        faces.append(tuple(range(nprof - 1, -1, -1)))
        end = (len(centers) - 1) * nprof
        faces.append(tuple(end + k for k in range(nprof)))
    mesh = bpy.data.meshes.new("continuous U-channel mesh")
    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("track_piece_with_scoop_discharge_chute", mesh)
    v4._link(obj)
    v4.assign(obj, teal)
    bevel = obj.modifiers.new("rounded channel lips", "BEVEL")
    bevel.width = 0.0007
    bevel.segments = 2
    bevel.limit_method = "ANGLE"
    obj.modifiers.new("track weighted normals", "WEIGHTED_NORMAL")
    v4.part(obj, frame)

    # Fine enamel highlights follow the two top lips and stay attached to the channel.
    for side in (-1, 1):
        lip_pts = []
        for i, p in enumerate(centers):
            prev = centers[max(0, i - 1)]
            nxt = centers[min(len(centers) - 1, i + 1)]
            dx, dy = nxt[0] - prev[0], nxt[1] - prev[1]
            ll = math.hypot(dx, dy)
            nx, ny = -dy / ll, dx / ll
            lip_pts.append((p[0] + nx * side * (half - wall / 2),
                            p[1] + ny * side * (half - wall / 2), p[2] + TRACK_H - 0.0004))
        v4.tube("channel_lip_inlay_" + str(side), lip_pts, 0.0011, material=teal_light, body=frame, resolution=3)
    return centers


def add_cupped_scoop(name, theta, cx, cz, y_center, material, body,
                      base_radius=0.101, tangent_width=0.046, axial_span=0.042,
                      lip_height=0.012, wall=0.004, floor=0.003):
    """Build one continuous U-section bucket extruded across the wheel axle width."""
    half = tangent_width / 2
    radial = (math.cos(theta), math.sin(theta))
    tangent = (-math.sin(theta), math.cos(theta))
    profile = [(-half, base_radius), (half, base_radius),
               (half, base_radius + lip_height), (half - wall, base_radius + lip_height),
               (half - wall, base_radius + floor), (-half + wall, base_radius + floor),
               (-half + wall, base_radius + lip_height), (-half, base_radius + lip_height)]
    verts = []
    for y in (y_center - axial_span / 2, y_center + axial_span / 2):
        for u, r in profile:
            verts.append((cx + tangent[0] * u + radial[0] * r,
                          y,
                          cz + tangent[1] * u + radial[1] * r))
    n = len(profile)
    faces = [tuple(range(n - 1, -1, -1)), tuple(range(n, 2 * n))]
    for i in range(n):
        j = (i + 1) % n
        faces.append((i, j, n + j, n + i))
    mesh = bpy.data.meshes.new(name + "_mesh")
    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._link(obj)
    v4.assign(obj, material)
    obj.data.materials.append(scoop_interior)
    # Darken the inset floor face so the molded U-shaped pocket reads from the front.
    if len(obj.data.polygons) > 6:
        obj.data.polygons[6].material_index = 1
    bevel = obj.modifiers.new("soft bucket edges", "BEVEL")
    bevel.width = 0.00045
    bevel.segments = 2
    bevel.limit_method = "ANGLE"
    obj.modifiers.new("bucket weighted normals", "WEIGHTED_NORMAL")
    v4.part(obj, body)
    return obj


def face_fastener(name, x, y, z, body, material=brass, radius=0.003):
    v4.cylinder(name, radius, 0.002, (x, y, z), rot=(math.pi / 2, 0, 0), segments=20,
                bevel=0.0002, material=material, body=body)
    # A fine straight slot makes the flush button read as a real screw head.
    v4.box(name + "_slot", (radius * 1.25, 0.0007, 0.00075), (x, y - 0.0011, z),
           bevel=0.0001, material=dark_steel, body=body)


# ---- Fixed wooden frame and lift column ----------------------------------------------
v4.box("base_laminated_core", (BASE_W, BASE_D, 0.030), (0, 0, 0.020), bevel=0.004,
       material=walnut, body=frame)
v4.box("beech_top_deck", (BASE_W - 0.016, BASE_D - 0.014, 0.008), (0, 0, 0.039), bevel=0.003,
       material=beech, body=frame)
v4.box("front_title_fascia", (BASE_W - 0.018, 0.010, 0.022), (0, -0.151, 0.021), bevel=0.002,
       material=endgrain, body=frame)
for sx in (-1, 1):
    for sy in (-1, 1):
        fx, fy = sx * 0.198, sy * 0.123
        v4.cylinder(f"rubber_isolator_{sx}_{sy}", 0.018, 0.008, (fx, fy, 0.004), segments=32,
                    bevel=0.001, material=rubber, body=frame)
        v4.cylinder(f"turned_beech_foot_{sx}_{sy}", 0.014, 0.008, (fx, fy, 0.010), segments=32,
                    bevel=0.001, material=beech, body=frame)

# Rear upright frame and back panel. The open front exposes the wheel and gears.
v4.box("rear_backboard", (0.420, 0.018, 0.477), (0, 0.131, 0.2815), bevel=0.003,
       material=walnut, body=frame)
for sx in (-1, 1):
    x = sx * 0.205
    v4.box(f"rear_frame_stile_{sx}", (0.026, 0.032, 0.492), (x, 0.105, 0.289), bevel=0.003,
           material=beech, body=frame)
    v4.box(f"front_lift_guide_{sx}", (0.011, 0.014, 0.355), (x, -0.007, 0.2205), bevel=0.002,
           material=walnut, body=frame)
v4.box("upper_header_rail", (0.446, 0.034, 0.024), (0, 0.105, 0.529), bevel=0.003,
       material=beech, body=frame)
v4.box("lower_backboard_sill", (0.424, 0.025, 0.020), (0, 0.112, 0.052), bevel=0.002,
       material=beech, body=frame)

# Two axle bearing blocks, bolted to the rear support, surround the shafts.
for label, x in (("crank", CRANK_X), ("wheel", WHEEL_X)):
    v4.box(label + "_rear_bearing_block", (0.048, 0.018, 0.048), (x, 0.112, SHAFT_Z),
           bevel=0.004, material=beech, body=frame)
    v4.cylinder(label + "_bearing_boss", 0.015, 0.010, (x, 0.099, SHAFT_Z),
                rot=(math.pi / 2, 0, 0), segments=40, bevel=0.001, material=dark_steel, body=frame)
    v4.torus(label + "_bronze_bearing_race", 0.010, 0.0018, (x, 0.092, SHAFT_Z),
             rot=(math.pi / 2, 0, 0), material=brass, body=frame)
    for sx in (-1, 1):
        for sz in (-1, 1):
            face_fastener(f"{label}_bearing_screw_{sx}_{sz}", x + sx * 0.016, 0.101,
                          SHAFT_Z + sz * 0.016, frame, steel, 0.0022)

# Fixed upper column cap and outlet catcher mounted above the paddle wheel.
v4.box("lift_column_top_brow", (0.302, 0.025, 0.017), (-0.075, 0.114, 0.369), bevel=0.003,
       material=beech, body=frame)

# Decorative top plaque on the rear board.
plaque = v4.box("raised_machine_nameplate", (0.172, 0.006, 0.038), (-0.075, 0.118, 0.476),
                bevel=0.002, material=navy, body=frame)
v4.text("nameplate_letters", "MARBLE LIFT  /  01", 0.013, loc=(-0.075, 0.1138, 0.476),
        rot=(math.pi / 2, 0, 0), material=ivory, body=frame, on=plaque, height=0.0006)

# Front title plus two small care symbols printed on the fascia.
v4.text("fascia_title", "CRANK  /  LIFT  /  ROLL", 0.014, loc=(0.002, -0.1562, 0.021),
        rot=(math.pi / 2, 0, 0), material=ivory, body=frame,
        on=bpy.data.objects["front_title_fascia"], height=0.0005)
for xx in (-0.204, 0.204):
    face_fastener("fascia_brass_pin_" + str(xx), xx, -0.157, 0.021, frame, brass, 0.0025)

# ---- Upper feed and descending fixed track -------------------------------------------
track_points = [
    # Raised lip at the wheel, followed by a short discharge ramp into the
    # lowered upper inlet, 20 mm below the original track floor.
    (-0.075, -0.034, 0.340), (-0.015, -0.050, 0.327), (0.020, -0.064, 0.322),
    (0.035, -0.064, 0.317), (0.075, -0.064, 0.309), (0.120, -0.055, 0.297),
    (0.151, -0.034, 0.281), (0.155, 0.008, 0.266), (0.143, 0.050, 0.253),
    (0.115, 0.075, 0.241), (0.090, 0.079, 0.229), (0.090, 0.045, 0.216),
    (0.093, -0.018, 0.202), (0.117, -0.066, 0.188), (0.161, -0.075, 0.174),
    (0.180, -0.037, 0.159), (0.180, 0.022, 0.144), (0.160, 0.064, 0.130),
    (0.132, 0.079, 0.117), (0.102, 0.054, 0.104), (0.100, -0.008, 0.092),
    (0.128, -0.060, 0.082), (0.170, -0.067, 0.077), (0.178, -0.027, 0.0745),
    (0.151, 0.028, 0.073), (0.102, 0.043, 0.072), (0.022, 0.043, 0.0715),
    (-0.060, 0.028, 0.071), (-0.080, 0.004, 0.069), (-0.080, -0.057, 0.067),
]
track_centers = add_track(track_points)
# A marble at the lowered inlet shows the discharge handoff into the fixed route.
v4.sphere("marble_at_discharge_inlet", 0.009, (0.020, -0.064, 0.331),
          segments=32, material=marble_orange, body=frame)

# The return cup now sits beneath the wheel, moved 60 mm right, 19 mm forward and 20 mm up.
v4.box("return_catch_floor", (0.072, 0.052, 0.005), (-0.075, -0.025, 0.070), bevel=0.002,
       material=teal, body=frame)
for sx in (-1, 1):
    v4.box(f"return_catch_side_{sx}", (0.004, 0.052, 0.009), (-0.075 + sx * 0.036, -0.025, 0.077),
           bevel=0.0015, material=teal, body=frame)

# Wooden columns rise from the deck to the underside of selected track turns.
for i in (6, 10, 14, 18, 22, 25):
    x, y, z = track_points[i]
    post_h = max(0.009, z - 0.045)
    v4.box(f"track_support_pier_{i}", (0.009, 0.009, post_h), (x, y, 0.045 + post_h / 2),
           bevel=0.001, material=beech, body=frame)
    v4.box(f"track_support_saddle_{i}", (0.024, 0.022, 0.004), (x, y, z - 0.0015),
           bevel=0.001, material=brass, body=frame)

# Three polished play marbles are staged at separated points on the downward route.
v4.sphere("marble_upper_orange", 0.009, (0.113, -0.055, 0.297 + TRACK_T + 0.009),
          segments=32, material=marble_orange, body=frame)
v4.sphere("marble_middle_yellow", 0.009, (0.093, -0.018, 0.202 + TRACK_T + 0.009),
          segments=32, material=marble_yellow, body=frame)
v4.sphere("marble_lower_blue", 0.009, (0.145, 0.032, 0.073 + TRACK_T + 0.009),
          segments=32, material=marble_blue, body=frame)

# ---- Crank and pinion: one continuous rotating assembly -------------------------------
crank_y_start, crank_y_end = -0.153, 0.120
v4.cylinder("crank_full_through_axle", 0.0065, crank_y_end - crank_y_start,
            (CRANK_X, (crank_y_start + crank_y_end) / 2, SHAFT_Z),
            rot=(math.pi / 2, 0, 0), segments=40, bevel=0.0005, material=steel, body=crank)
add_gear("crank_20_tooth_pinion", CRANK_X, SHAFT_Z, GEAR_Y, 20, PINION_R, 0.0028, 0.0, brass, crank)
v4.cylinder("pinion_face_hub", 0.012, 0.008, (CRANK_X, -0.143, SHAFT_Z),
            rot=(math.pi / 2, 0, 0), segments=40, bevel=0.001, material=steel, body=crank)
for i in range(5):
    a = i * 2 * math.pi / 5
    v4.cylinder(f"pinion_rivet_{i}", 0.0017, 0.0018,
                (CRANK_X + 0.0085 * math.cos(a), -0.148, SHAFT_Z + 0.0085 * math.sin(a)),
                rot=(math.pi / 2, 0, 0), segments=16, bevel=0.0002, material=brass, body=crank)

# Crank arm is a forged web with a turned grip at its outer end.
grip_x, grip_z = CRANK_X - 0.048, SHAFT_Z + 0.045
v4.rod("crank_arm_web", (CRANK_X, -0.157, SHAFT_Z), (grip_x, -0.157, grip_z), 0.0065,
       segments=24, bevel=0.0005, material=navy, body=crank)
v4.cylinder("crank_grip_pin", 0.0045, 0.032, (grip_x, -0.166, grip_z),
            rot=(math.pi / 2, 0, 0), segments=28, bevel=0.0005, material=brass, body=crank)
v4.lathe("turned_wood_crank_handle", [(0, -0.024), (0.006, -0.024), (0.009, -0.018),
                                      (0.010, -0.010), (0.009, 0.012), (0.006, 0.020), (0, 0.020)],
         loc=(grip_x, -0.166, grip_z), rot=(math.pi / 2, 0, 0), material=beech, body=crank)
v4.cylinder("crank_end_cap", 0.0075, 0.003, (grip_x, -0.1875, grip_z),
            rot=(math.pi / 2, 0, 0), segments=28, bevel=0.0008, material=brass, body=crank)

# ---- Large drive gear and paddle wheel share one axle/body ----------------------------
lift_y_start, lift_y_end = -0.144, 0.120
v4.cylinder("paddle_wheel_through_axle", 0.007, lift_y_end - lift_y_start,
            (WHEEL_X, (lift_y_start + lift_y_end) / 2, WHEEL_Z),
            rot=(math.pi / 2, 0, 0), segments=44, bevel=0.0005, material=steel, body=lift)
add_gear("lift_36_tooth_gear", WHEEL_X, WHEEL_Z, GEAR_Y, 36, DRIVE_R, 0.0028,
         math.pi / 36, navy, lift)
v4.cylinder("drive_gear_face_hub", 0.020, 0.008, (WHEEL_X, -0.143, WHEEL_Z),
            rot=(math.pi / 2, 0, 0), segments=48, bevel=0.001, material=brass, body=lift)
v4.cylinder("hub_lock_nut", 0.009, 0.006, (WHEEL_X, -0.150, WHEEL_Z),
            rot=(math.pi / 2, 0, 0), segments=6, bevel=0.0006, material=steel, body=lift)
for i in range(6):
    a = i * 2 * math.pi / 6 + math.pi / 6
    v4.cylinder(f"drive_gear_face_rivet_{i}", 0.0020, 0.002,
                (WHEEL_X + 0.014 * math.cos(a), -0.148, WHEEL_Z + 0.014 * math.sin(a)),
                rot=(math.pi / 2, 0, 0), segments=16, bevel=0.0002, material=steel, body=lift)

WHEEL_R = 0.126
for side_y in (-0.050, 0.000):
    v4.torus("paddle_wheel_rim_" + str(side_y), WHEEL_R - 0.004, 0.0045,
             (WHEEL_X, side_y, WHEEL_Z), rot=(math.pi / 2, 0, 0), material=red, body=lift)
    for i in range(8):
        a = i * 2 * math.pi / 8
        p0 = (WHEEL_X + 0.020 * math.cos(a), side_y, WHEEL_Z + 0.020 * math.sin(a))
        p1 = (WHEEL_X + (WHEEL_R - 0.004) * math.cos(a), side_y, WHEEL_Z + (WHEEL_R - 0.004) * math.sin(a))
        v4.rod(f"wheel_spoke_{side_y}_{i}", p0, p1, 0.0032, segments=20, bevel=0.0003,
               material=brass if i % 2 == 0 else red, body=lift)

# Axial tie bars join both wheel rims into one rigid cage, as on a small elevator wheel.
for i in range(8):
    a = i * 2 * math.pi / 8
    tx = WHEEL_X + (WHEEL_R - 0.004) * math.cos(a)
    tz = WHEEL_Z + (WHEEL_R - 0.004) * math.sin(a)
    v4.rod(f"rim_axial_tie_{i}", (tx, -0.052, tz), (tx, 0.002, tz), 0.0038,
           segments=20, bevel=0.0003, material=brass, body=lift)

# Eight broad U-section scoops span the 40 mm opening between the wheel rims.
# Their 10 mm radial lips keep 18 mm play marbles seated during the rising arc.
for i in range(8):
    a = i * 2 * math.pi / 8
    add_cupped_scoop(f"paddle_scoop_{i}", a, WHEEL_X, WHEEL_Z, WHEEL_Y,
                      yellow_enamel if i == 0 else red, lift)

# A fixed annular guard follows the ascending half of the wheel with 4.5 mm
# clearance from the wheel cage while keeping the rising marbles enclosed.
guide_inner, guide_outer = 0.131, 0.137
arc_start, arc_end = math.radians(118), math.radians(242)
guide_outline = []
for i in range(33):
    a = arc_start + (arc_end - arc_start) * i / 32
    guide_outline.append((WHEEL_X + guide_inner * math.cos(a), WHEEL_Z + guide_inner * math.sin(a)))
for i in range(32, -1, -1):
    a = arc_start + (arc_end - arc_start) * i / 32
    guide_outline.append((WHEEL_X + guide_outer * math.cos(a), WHEEL_Z + guide_outer * math.sin(a)))
extruded_polygon("ascending_side_marble_guide", guide_outline, WHEEL_Y, 0.040,
                 aqua_guard, frame, 0.0005)
for i, a in enumerate((arc_start, arc_end)):
    x = WHEEL_X + (guide_inner + guide_outer) * 0.5 * math.cos(a)
    z = WHEEL_Z + (guide_inner + guide_outer) * 0.5 * math.sin(a)
    v4.rod(f"ascending_guide_rear_standoff_{i}", (x, -0.006, z), (x, 0.121, z), 0.0022,
           segments=20, bevel=0.0003, material=brass, body=frame)

# Two balls ride in separate pockets to show the lift action on its ascending side.
for i, a in enumerate((math.radians(225), math.radians(180))):
    r = 0.1125
    v4.sphere(f"marble_in_lift_scoop_{i}", 0.009,
              (WHEEL_X + r * math.cos(a), WHEEL_Y, WHEEL_Z + r * math.sin(a)),
              segments=32, material=marble_yellow if i == 0 else marble_blue, body=lift)

v4.cylinder("wheel_front_hub", 0.021, 0.014, (WHEEL_X, -0.058, WHEEL_Z),
            rot=(math.pi / 2, 0, 0), segments=48, bevel=0.0015, material=red, body=lift)
v4.cylinder("wheel_center_medallion", 0.013, 0.004, (WHEEL_X, -0.067, WHEEL_Z),
            rot=(math.pi / 2, 0, 0), segments=40, bevel=0.001, material=brass, body=lift)
v4.cylinder("wheel_center_dark_inset", 0.008, 0.002, (WHEEL_X, -0.070, WHEEL_Z),
            rot=(math.pi / 2, 0, 0), segments=40, bevel=0.0005, material=navy, body=lift)
v4.cylinder("wheel_rear_hub", 0.021, 0.014, (WHEEL_X, 0.008, WHEEL_Z),
            rot=(math.pi / 2, 0, 0), segments=44, bevel=0.001, material=red, body=lift)

# ---- Limited-motion pivot gate on the feed track -------------------------------------
GATE_X, GATE_Y, GATE_Z = 0.018, -0.095, 0.333
v4.cylinder("gate_fixed_bearing_pin", 0.004, 0.018, (GATE_X, GATE_Y, GATE_Z),
            segments=28, bevel=0.0005, material=brass, body=frame)
v4.torus("gate_fixed_bearing_race", 0.0055, 0.0018, (GATE_X, GATE_Y, GATE_Z + 0.006),
         material=steel, body=frame)
# Raised brass L-bracket anchors the hinge to the fixed channel lip, above the gate bar.
v4.rod("gate_bearing_bridge", (GATE_X, GATE_Y, GATE_Z + 0.011),
       (GATE_X, -0.082, GATE_Z + 0.011), 0.003, segments=20, bevel=0.0003,
       material=brass, body=frame)
v4.rod("gate_bearing_bridge_leg", (GATE_X, -0.082, GATE_Z + 0.011),
       (GATE_X, -0.082, GATE_Z + 0.004), 0.003, segments=20, bevel=0.0003,
       material=brass, body=frame)
v4.cylinder("gate_rotating_hub", 0.006, 0.012, (GATE_X, GATE_Y, GATE_Z),
            segments=28, bevel=0.0008, material=navy, body=gate)
v4.rod("gate_crossbar", (GATE_X, GATE_Y, GATE_Z), (GATE_X, -0.030, GATE_Z), 0.0025,
       segments=20, bevel=0.0003, material=brass, body=gate)
v4.sphere("gate_end_bob", 0.0042, (GATE_X, -0.030, GATE_Z), segments=24, material=red, body=gate)
v4.rod("gate_top_lever", (GATE_X, GATE_Y, GATE_Z + 0.003),
       (GATE_X - 0.006, GATE_Y - 0.019, GATE_Z + 0.020), 0.0020,
       segments=20, bevel=0.0003, material=steel, body=gate)
v4.sphere("gate_finger_knob", 0.0045, (GATE_X - 0.006, GATE_Y - 0.019, GATE_Z + 0.020),
          segments=24, material=red, body=gate)

# Metal stop tabs and small indexing marks are fixed to the channel support.
v4.box("gate_closed_stop", (0.012, 0.008, 0.006), (GATE_X - 0.006, GATE_Y, GATE_Z - 0.010),
       bevel=0.001, material=brass, body=frame)
v4.box("gate_open_stop", (0.012, 0.008, 0.006), (GATE_X + 0.006, GATE_Y, GATE_Z - 0.010),
       bevel=0.001, material=brass, body=frame)

# Explicit articulated joints. Gear ratio is a visual/mechanical representation only:
# Articraft has no gear-ratio constraint, so both shafts retain valid independent revolutes.
v4.joint("crank_turn", "continuous", frame, crank, origin=(CRANK_X, -0.132, SHAFT_Z), axis=(0, 1, 0))
v4.joint("paddle_drive", "continuous", frame, lift, origin=(WHEEL_X, -0.132, WHEEL_Z), axis=(0, 1, 0))
v4.joint("feed_gate", "revolute", frame, gate, origin=(GATE_X, GATE_Y, GATE_Z), axis=(0, 0, 1),
         limits=(-1.40, 0.0))

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