"""Detailed two-wheel self-balancing transporter; run with Blender -b --python build.py."""
import math
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import v4lib as v4

v4.reset()

# Materials: durable charcoal shell, elastomer contact surfaces, and restrained hardware.
shell = v4.plastic("graphite_polymer", (0.075, 0.085, 0.095), roughness=0.34, texture=0.12)
panel = v4.plastic("satin_black_panel", (0.035, 0.042, 0.048), roughness=0.42, texture=0.18)
rubber = v4.rubber("tire_rubber", (0.018, 0.02, 0.022), roughness=0.84)
padmat = v4.rubber("foot_grip_rubber", (0.045, 0.052, 0.056), roughness=0.8)
alloy = v4.metal("brushed_aluminum", (0.62, 0.66, 0.69), roughness=0.28)
darkmetal = v4.metal("dark_motor_alloy", (0.16, 0.18, 0.20), roughness=0.31)
displaymat = v4.emissive("cool_display", (0.12, 0.55, 0.9), strength=1.2)
orange = v4.painted("safety_orange", (0.92, 0.24, 0.035), roughness=0.3, coat=0.45)
white = v4.mat("warm_white_print", (0.82, 0.84, 0.82), roughness=0.5)
red = v4.painted("rear_reflector_red", (0.55, 0.025, 0.018), roughness=0.22)
led = v4.emissive("status_amber_led", (1.0, 0.31, 0.025), strength=2.0)

# Primary dimensions (metres): large 0.44 m wheels, 0.27 m deck, 1.13 m overall.
# Raising the root lifts axle and deck together while keeping the enlarged tires on ground.
DECK_LIFT = 0.06
wheel_r, wheel_z, axle = 0.22, 0.16, 0.22
chassis = v4.body("chassis")

# Main bridge and deck shell, with a lower battery tray connecting the hub mounts.
v4.box("deck_shell", (0.39, 0.27, 0.075), (0, 0, 0.286), bevel=0.020, material=shell, body=chassis)
# Raised narrow deck rails frame the pads while leaving their tilt envelope clear.
for sx, side in [(-1, "L"), (1, "R")]:
    v4.box(f"deck_side_rail_{side}", (0.009, 0.23, 0.060), (sx*0.1905, 0, 0.337),
           bevel=0.004, material=shell, body=chassis)
v4.box("underside_battery_tray", (0.29, 0.20, 0.047), (0, 0.012, 0.256), bevel=0.012, material=panel, body=chassis)
# Rounded battery belly layered under the deck bridge.
v4.box("battery_housing_shell", (0.30, 0.218, 0.075), (0, 0.012, 0.235), bevel=0.022, material=panel, body=chassis)
# Continuous molded center shell gives the bridge a fuller, softened enclosure.
v4.box("molded_chassis_body_shell", (0.35, 0.245, 0.092), (0, 0.008, 0.271),
       bevel=0.028, material=shell, body=chassis)
v4.box("front_bumper", (0.35, 0.026, 0.045), (0, -0.143, 0.302), bevel=0.012, material=panel, body=chassis)
v4.box("rear_bumper", (0.35, 0.026, 0.045), (0, 0.143, 0.302), bevel=0.012, material=panel, body=chassis)
# Motor bearing bosses protrude to each inner tire face, making the axle mounting legible.
for sx, side in [(-1, "L"), (1, "R")]:
    # A narrow structural web links the deck down to the motor bearing without
    # crossing the tire's inner sidewall.
    v4.box(f"motor_mount_web_{side}", (0.030, 0.090, 0.174), (sx*0.158, 0, 0.235),
           bevel=0.009, material=shell, body=chassis)
    v4.cylinder(f"bearing_boss_{side}", 0.057, 0.008, (sx * 0.172, 0, wheel_z), rot=(0, math.pi/2, 0),
                material=darkmetal, body=chassis)
# Rearward yoke supports rise from the shell behind the pad heels, leaving the tilt envelope clear.
for sx, side in [(-1, "L"), (1, "R")]:
    v4.box(f"stalk_yoke_support_{side}", (0.024, 0.030, 0.080), (sx*0.042, 0.127, 0.360),
           bevel=0.006, material=darkmetal, body=chassis)
yoke = v4.box("stalk_bearing_yoke", (0.09, 0.012, 0.060), (0, 0.11, 0.426),
              bevel=0.008, material=shell, body=chassis)
yoke_opening = v4.box("stalk_bearing_yoke_opening", (0.050, 0.020, 0.064), (0, 0.11, 0.426), bevel=0)
v4.boolean(yoke, yoke_opening)
for sx, side in [(-1, "L"), (1, "R")]:
    v4.cylinder(f"stalk_yoke_bearing_cap_{side}", 0.010, 0.012, (sx*0.038, 0.11, 0.414),
                rot=(math.pi/2, 0, 0), material=darkmetal, body=chassis)
    v4.torus(f"stalk_yoke_bearing_rim_{side}", 0.007, 0.002, (sx*0.038, 0.102, 0.414),
             rot=(math.pi/2, 0, 0), material=alloy, body=chassis)
# The pivot is defined by the accepted joint; the exposed trunnion is omitted under this housing.
# Pad hinge brackets rise from the deck under the midpoint of each pad, directly
# over the wheel axle line. The pad mounted pivot barrels rest on these saddles.
for sx, side in [(-1, "L"), (1, "R")]:
    v4.box(f"pad_hinge_bracket_{side}", (0.12, 0.020, 0.040), (sx*0.098, 0, 0.325), bevel=0.005, material=darkmetal, body=chassis)
# Thin side service covers and inset seams.
for sx, side in [(-1, "L"), (1, "R")]:
    v4.box(f"side_service_cover_{side}", (0.006, 0.15, 0.036), (sx*0.184, 0.004, 0.345),
           bevel=0.008, material=darkmetal, body=chassis)
    for k in range(3):
        v4.box(f"side_vent_{side}_{k}", (0.002, 0.022, 0.0025), (sx*0.188, -0.035+k*0.035, 0.345),
               bevel=0.001, material=panel, body=chassis)
    for sy in (-1, 1):
        v4.cylinder(f"side_panel_screw_{side}_{sy}", 0.003, 0.002, (sx*0.188, sy*0.060, 0.345),
                    rot=(0, math.pi/2, 0), segments=16, bevel=0.0003, material=alloy, body=chassis)
# Full-width front light bar and rear reflector mounted into the bumper faces.
v4.box("front_light_bezel", (0.205, 0.006, 0.026), (0, -0.157, 0.304), bevel=0.008, material=darkmetal, body=chassis)
v4.box("front_marker_lens", (0.178, 0.004, 0.012), (0, -0.161, 0.304), bevel=0.004, material=led, body=chassis)
v4.box("rear_reflector", (0.09, 0.004, 0.018), (0, 0.157, 0.304), bevel=0.005, material=red, body=chassis)
# Raised kick-plate lip below the front fascia.
v4.box("front_kick_plate_lip", (0.32, 0.014, 0.018), (0, -0.157, 0.278), bevel=0.005, material=panel, body=chassis)
# A narrow center spine fills the gap without entering either pad's tilt envelope.
v4.box("footpad_center_spine", (0.020, 0.192, 0.058), (0, -0.0025, 0.3495),
       bevel=0.008, material=panel, body=chassis)
# Chassis foot-pad hinge line hardware and stalk pivot socket.
# Four low-profile screws anchor the battery tray.
for sx in (-1, 1):
    for sy in (-1, 1):
        v4.cylinder(f"tray_screw_{sx}_{sy}", 0.004, 0.002, (sx*0.116, sy*0.074, 0.233),
                    material=alloy, segments=16, bevel=0.0003, body=chassis)

# Molded curved fender shells clear the tread and overlap the reinforced deck rails.
# Each shell is a single closed mesh so it remains a connected chassis component.
for sx, side in [(-1, "L"), (1, "R")]:
    import bpy
    n = 41
    xlo, xhi = sx*0.198-0.009, sx*0.198+0.009
    verts = []
    for i in range(n):
        a = math.radians(-70 + 140*i/(n-1))
        for radius, x in ((0.238,xlo),(0.226,xlo),(0.238,xhi),(0.226,xhi)):
            verts.append((x, radius*math.sin(a), wheel_z + radius*math.cos(a)))
    faces = []
    for i in range(n-1):
        b, q = 4*i, 4*(i+1)
        faces.extend(((b,q,q+2,b+2), (b+1,b+3,q+3,q+1),
                      (b,b+1,q+1,q), (b+2,q+2,q+3,b+3)))
    faces.extend(((0,2,3,1), (4*(n-1),4*(n-1)+1,4*(n-1)+3,4*(n-1)+2)))
    mesh = bpy.data.meshes.new(f"wheel_fender_arch_{side}_mesh")
    mesh.from_pydata(verts, [], faces)
    mesh.update()
    arch = bpy.data.objects.new(f"wheel_fender_arch_{side}", mesh)
    v4._finish(arch, chassis, panel, bevel=0.001, smooth=True)

# Independently powered wheels; cylinder axes are X and the hubs are part of each wheel body.
for sx, side in [(-1, "left"), (1, "right")]:
    wheel = v4.body(f"{side}_wheel")
    cx = sx * axle
    v4.cylinder(f"{side}_tire", wheel_r, 0.050, (cx, 0, wheel_z), rot=(0, math.pi/2, 0),
                segments=96, bevel=0.009, material=rubber, body=wheel)
    # Raised sidewall bead rings on both tire faces.
    for face in (-1, 1):
        fx = cx + face*0.0255
        v4.torus(f"{side}_sidewall_bead_{face}", 0.128, 0.0022, (fx, 0, wheel_z),
                 rot=(0, math.pi/2, 0), material=panel, body=wheel)
        v4.cylinder(f"{side}_motor_cover_{face}", 0.092, 0.010, (cx+face*0.030, 0, wheel_z),
                    rot=(0, math.pi/2, 0), material=darkmetal, body=wheel)
        v4.cylinder(f"{side}_hub_recess_{face}", 0.064, 0.004, (cx+face*0.036, 0, wheel_z),
                    rot=(0, math.pi/2, 0), material=panel, body=wheel)
        v4.torus(f"{side}_rim_lip_{face}", 0.061, 0.003, (cx+face*0.039, 0, wheel_z),
                 rot=(0, math.pi/2, 0), material=alloy, body=wheel)
        v4.cylinder(f"{side}_axle_cap_{face}", 0.027, 0.008, (cx+face*0.040, 0, wheel_z),
                    rot=(0, math.pi/2, 0), material=panel, body=wheel)
        # Six radial recess/bolt details on each hub ring.
        for k in range(6):
            a = 2*math.pi*k/6
            v4.cylinder(f"{side}_hub_screw_{face}_{k}", 0.0032, 0.002,
                        (cx+face*0.040, 0.048*math.sin(a), wheel_z+0.048*math.cos(a)),
                        rot=(0, math.pi/2, 0), segments=12, bevel=0.0002, material=alloy, body=wheel)
        # Machined radial spokes bridge the recessed hub ring to the axle cap.
        for k in range(8):
            a = 2*math.pi*k/8
            v4.rod(f"{side}_hub_spoke_{face}_{k}",
                   (cx+face*0.039, 0.027*math.sin(a), wheel_z+0.027*math.cos(a)),
                   (cx+face*0.039, 0.060*math.sin(a), wheel_z+0.060*math.cos(a)),
                   0.0042, material=alloy, body=wheel)
    # Inner motor stator cover is visible between tire and chassis bearing web.
    inner_face = 1 if sx < 0 else -1
    v4.cylinder(f"{side}_inner_motor_housing", 0.073, 0.012,
                (cx+inner_face*0.033, 0, wheel_z), rot=(0, math.pi/2, 0),
                material=darkmetal, body=wheel)
    v4.torus(f"{side}_inner_motor_seal", 0.064, 0.0025,
             (cx+inner_face*0.040, 0, wheel_z), rot=(0, math.pi/2, 0),
             material=alloy, body=wheel)
    # Subtle continuous circumferential tread ribs replace the chunky lug blocks.
    for k, offset in enumerate((-0.014, 0.0, 0.014)):
        v4.torus(f"{side}_tread_rib_{k}", 0.2205, 0.0012, (cx+offset, 0, wheel_z),
                 rot=(0, math.pi/2, 0), material=panel, body=wheel)
    # Small model marking on the outward side cap.
    v4.joint(f"{side}_drive", "continuous", chassis, wheel, origin=(cx, 0, wheel_z), axis=(sx, 0, 0))

# Separate tilt-sensitive standing pads, each mounted on its rear transverse hinge line.
for sx, side in [(-1, "left"), (1, "right")]:
    pad = v4.body(f"{side}_pad")
    # Each pad occupies its own half of the deck with a narrow center gap.
    x0, x1 = (sx*0.184, sx*0.012)
    xa, xb = min(x0, x1), max(x0, x1)
    width = xb-xa
    xc = (xa+xb)/2
    v4.box(f"{side}_pad_carrier", (width, 0.215, 0.014), (xc, -0.0025, 0.361),
           bevel=0.008, material=darkmetal, body=pad)
    v4.box(f"{side}_pad_grip_surface", (width-0.012, 0.194, 0.008), (xc, -0.0025, 0.372),
           bevel=0.006, material=padmat, body=pad)
    # Soft raised rubber perimeter bumpers protect the standing surface edges.
    v4.box(f"{side}_pad_outer_bumper", (0.018, 0.198, 0.010), (sx*0.173, -0.0025, 0.372),
           bevel=0.005, material=rubber, body=pad)
    # Raised transverse ribs molded into the standing surface.
    for k in range(7):
        yy = -0.077 + k*0.025
        v4.box(f"{side}_grip_rib_{k}", (width-0.026, 0.004, 0.0025), (xc, yy, 0.377),
               bevel=0.001, material=panel, body=pad)
    # Contrasting side safety strips sit flush along outer edges.
    edge_x = sx*(0.184-0.007)
    v4.box(f"{side}_safety_edge", (0.004, 0.175, 0.003), (edge_x, -0.0025, 0.3775),
           bevel=0.001, material=orange, body=pad)
    # Two pivot barrels sit on the pad underside at the axle line.
    for hx in (sx*0.074, sx*0.152):
        v4.cylinder(f"{side}_pad_knuckle_{hx:.3f}", 0.009, 0.036, (hx, 0, 0.354),
                    rot=(0, math.pi/2, 0), material=alloy, body=pad)
    v4.joint(f"{side}_pad_hinge", "revolute", chassis, pad,
             origin=(xc, 0, 0.354), axis=(1, 0, 0), limits=(-math.radians(6), math.radians(6)))

# Pivoting steering / lean column. All stalk, grip and control details are one rigid assembly.
stalk = v4.body("control_stalk")
# The coaxial socket at the accepted pivot meets the widened column tube directly.
v4.cylinder("stalk_lower_socket", 0.0265, 0.022, (0, 0.11, 0.39),
            rot=(math.pi/2, 0, 0), segments=48, bevel=0, material=darkmetal, body=stalk)
# Slanted aluminum column with lower and upper telescoping sleeves.
v4.rod("stalk_main_tube", (0, 0.143, 0.405), (0, 0.185, 0.995), 0.026,
       material=shell, body=stalk, bevel=0.002)
# Three close accordion rings over the socket make the side-lean joint read as a
# sealed, flexible steering boot while remaining part of the stalk assembly.
for i, z in enumerate((0.442, 0.454, 0.466)):
    y = 0.145 + (z-0.435)*0.0714
    v4.torus(f"stalk_lean_boot_rib_{i}", 0.0285, 0.0045, (0, y, z),
             material=panel, body=stalk)
v4.rod("stalk_lower_machined_sleeve", (0, 0.146, 0.47), (0, 0.151, 0.555), 0.031,
       material=darkmetal, body=stalk)
v4.rod("stalk_upper_collar", (0, 0.179, 0.91), (0, 0.184, 0.965), 0.030,
       material=alloy, body=stalk)
# Handlebar runs left-right with soft grips, metal end caps and thumb controls.
v4.rod("handlebar_riser", (0, 0.185, 0.974), (0, 0.185, 1.054), 0.014,
       material=alloy, body=stalk)
# One continuous turned handle assembly: thin alloy core, with integral thickened
# elastomer grip zones so no hidden nested solids can separate from the bar.
handle = v4.lathe("handlebar_with_grips", [(0,-0.218),(0.022,-0.218),(0.024,-0.211),(0.021,-0.205),
    (0.024,-0.198),(0.024,-0.112),(0.020,-0.106),(0.012,-0.098),(0.012,0.098),
    (0.020,0.106),(0.024,0.112),(0.024,0.198),(0.021,0.205),(0.024,0.211),(0.022,0.218),(0,0.218)],
    loc=(0,0.185,1.045), rot=(0,math.pi/2,0), material=rubber, body=stalk)
# Satin metal is visible only on the central, narrow section of the single mesh.
handle.data.materials.append(alloy)
for poly in handle.data.polygons:
    zc = sum(handle.data.vertices[i].co.z for i in poly.vertices)/len(poly.vertices)
    if abs(zc) < 0.102:
        poly.material_index = 1
for sx, side in [(-1, "left"), (1, "right")]:
    pass
# Compact display/key pod at the handlebar center, facing the rider (+Y).
v4.box("handle_display_pod", (0.078, 0.044, 0.043), (0, 0.151, 1.052), bevel=0.010, material=panel, body=stalk)
v4.box("handle_display_bezel", (0.052, 0.006, 0.024), (0, 0.126, 1.053), bevel=0.004, material=darkmetal, body=stalk)
v4.box("handle_display_screen", (0.042, 0.003, 0.015), (0, 0.122, 1.054), bevel=0.002, material=displaymat, body=stalk)
v4.cylinder("handle_key_button", 0.006, 0.004, (0.029, 0.126, 1.052),
            rot=(math.pi/2, 0, 0), segments=20, bevel=0.001, material=orange, body=stalk)
# Small amber status repeater on the front face of the column.
v4.box("stalk_status_lens", (0.034, 0.004, 0.010), (0, 0.158, 0.928), bevel=0.003, material=led, body=stalk)
v4.joint("stalk_lean", "revolute", chassis, stalk, origin=(0, 0.11, 0.39), axis=(0, 1, 0),
         limits=(-math.radians(12), math.radians(12)))

# Top-deck branding sits centered and raised just above the deck/pad plane.

chassis.location.z = DECK_LIFT
v4.save(os.path.join(os.getcwd(), "asset.blend"))
print("saved asset.blend")
