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

v4.reset()
# Powder-coated frame, stainless rails, elastomer and upholstery.
frame_black = v4.painted('Graphite powder coat', (0.055, 0.075, 0.09), roughness=0.34)
black = v4.painted('Satin black steel', (0.025, 0.03, 0.035), roughness=0.38)
steel = v4.metal('Satin machined steel', (0.34, 0.39, 0.42), roughness=0.4)
chrome = v4.metal('Bright zinc hardware', (0.55, 0.59, 0.61), roughness=0.32, brushed=False)
platform = v4.painted('Textured graphite foot platform', (0.018, 0.025, 0.030), roughness=0.62)
warning = v4.painted('Safety amber', (0.95, 0.36, 0.035), roughness=0.35)
red = v4.painted('Safety red', (0.78, 0.055, 0.035), roughness=0.27)
rubber = v4.rubber('Foot and grip rubber', (0.025, 0.03, 0.033))
traction = v4.rubber('Textured traction rubber', (0.09, 0.105, 0.11))
padmat = v4.fabric('Black upholstery', (0.035, 0.042, 0.047))
stitch = v4.mat('Stitching', (0.2, 0.21, 0.22), roughness=0.82)
label = v4.mat('Warm white lettering', (0.86, 0.82, 0.68), roughness=0.5)

frame = v4.body('frame')
# Main welded base: 1.42 m wide, 2.0 m long.
for y, nm in [(-0.94, 'front'), (0.88, 'rear')]:
    v4.box(f'{nm}_crossfoot', (1.42, 0.12, 0.10), (0, y, 0.10), bevel=0.025, material=frame_black, body=frame)
    for sx in (-1, 1):
        v4.box(f'{nm}_rubber_foot_{sx}', (0.24, 0.18, 0.04), (sx*0.52, y, 0.045), bevel=0.012, material=rubber, body=frame)
# Side base rails and rear uprights.
for sx in (-1, 1):
    x = sx*0.59
    v4.rod(f'base_longitudinal_{sx}', (x,-0.88,0.15), (x,0.82,0.15), 0.045, square=True, bevel=0.008, material=frame_black, body=frame)
    v4.rod(f'rear_upright_{sx}', (x,0.76,0.12), (x,0.68,1.70), 0.043, square=True, bevel=0.007, material=frame_black, body=frame)
    rx=sx*0.49
    v4.rod(f'upper_brace_{sx}', (sx*0.59,0.61,1.15), (x,0.68,1.70), 0.03, square=True, bevel=0.005, material=frame_black, body=frame)
# Rail centerline; from the low rear seat toward the high front footplate.
d = (0.0, -math.sqrt(0.5), math.sqrt(0.5))
side_normal = (0.0, math.sqrt(0.5), math.sqrt(0.5))
rail_start = (0.0, 0.86, 0.34)
rail_len = 2.10
rail_end = tuple(rail_start[i] + rail_len*d[i] for i in range(3))
for sx in (-1,1):
    p0=(sx*0.49,rail_start[1],rail_start[2]); p1=(sx*0.49,rail_end[1],rail_end[2])
    v4.rod(f'guide_rail_{sx}',p0,p1,0.027,material=steel,bevel=0.001,body=frame)
    v4.rod(f'rail_support_{sx}',(sx*0.72,0.80,0.16),(sx*0.72,rail_end[1]+0.06,rail_end[2]-0.06),0.035,square=True,bevel=0.006,material=frame_black,body=frame)
    v4.rod(f'lower_rail_mount_{sx}',(sx*0.59,0.88,0.12),p0,0.035,square=True,bevel=0.004,material=frame_black,body=frame)
    v4.rod(f'upper_rail_tie_{sx}',(sx*0.72,rail_end[1],rail_end[2]),(sx*0.47,rail_end[1],rail_end[2]),0.032,square=True,bevel=0.004,material=frame_black,body=frame)
    v4.rod(f'upper_rail_rear_brace_{sx}',(sx*0.72,rail_end[1],rail_end[2]),(sx*0.59,0.68,1.68),0.032,square=True,bevel=0.004,material=frame_black,body=frame)
    # Triangular weld doublers bridge the upper tie to the diagonal frame members.
    gusset_outline=[(-0.12,0.0),(0.12,0.0),(0.12,-0.17)]
    gusset_y=rail_end[1]+0.018
    gusset_z=rail_end[2]
    v4.extrude(f'upper_joint_gusset_{sx}',gusset_outline,0.014,loc=(sx*0.60,gusset_y,gusset_z),rot=(math.pi/2,0,0),bevel=0.006,material=steel,body=frame)
    for dx,dz in [(-0.075,-0.028),(0.075,-0.125)]:
        v4.cylinder(f'upper_gusset_bolt_{sx}_{dx}',0.012,0.014,(sx*0.60+dx,gusset_y+0.008,gusset_z+dz),rot=(math.pi/2,0,0),material=chrome,body=frame)
    # Welded end plugs and subtle corner fasteners finish the powder-coated tubes.
    v4.box(f'upright_end_cap_{sx}',(0.092,0.092,0.018),(sx*0.59,0.68,1.705),bevel=0.009,material=black,body=frame)
    v4.box(f'front_foot_end_cap_{sx}',(0.018,0.125,0.082),(sx*0.71,-0.94,0.10),bevel=0.012,material=black,body=frame)
    v4.cylinder(f'rail_mount_bolt_{sx}',0.014,0.012,(sx*0.72,rail_end[1],rail_end[2]),rot=(0,math.pi/2,0),material=chrome,body=frame)
# Seat support structure, flat seat pan and upholstered bottom cushion.
v4.rod('seat_lower_crossbrace',(-0.62,0.66,0.20),(0.62,0.66,0.20),0.035,square=True,bevel=0.006,material=frame_black,body=frame)
for sx in (-1,1):
    v4.rod(f'seat_stanchion_{sx}',(sx*0.39,0.66,0.18),(sx*0.39,0.58,0.40),0.035,square=True,bevel=0.006,material=frame_black,body=frame)
v4.box('seat_cross_support',(0.92,0.12,0.095),(0,0.58,0.36),bevel=0.012,material=frame_black,body=frame)
v4.box('seat_pan',(0.58,0.49,0.065),(0,0.66,0.425),bevel=0.025,material=black,body=frame)
v4.box('seat_cushion',(0.54,0.45,0.105),(0,0.66,0.50),bevel=0.045,material=padmat,body=frame)
# Stitched perimeter and a shallow crown panel finish the upholstered seat top.
for sx in (-1,1):
    v4.rod(f'seat_stitch_side_{sx}',(sx*0.22,0.49,0.556),(sx*0.22,0.83,0.556),0.008,material=stitch,body=frame)
for y in (0.51,0.81):
    v4.rod(f'seat_stitch_cross_{y}',(-0.22,y,0.556),(0.22,y,0.556),0.006,material=stitch,body=frame)
v4.box('seat_crown_panel',(0.42,0.30,0.012),(0,0.66,0.557),bevel=0.055,material=padmat,body=frame)
# Fold-away grab handles beside the hips: steel stalks with thick rubber sleeves.
for sx in (-1,1):
    v4.rod(f'seat_handle_standoff_{sx}',(sx*0.25,0.61,0.53),(sx*0.43,0.61,0.53),0.018,material=chrome,body=frame)
    v4.rod(f'seat_grab_handle_{sx}',(sx*0.43,0.61,0.51),(sx*0.43,0.61,0.74),0.014,material=frame_black,body=frame)
    v4.cylinder(f'seat_grab_grip_{sx}',0.027,0.17,(sx*0.43,0.61,0.625),material=rubber,body=frame)
    for z in (0.525,0.545):
        v4.cylinder(f'seat_handle_bolt_{sx}_{z}',0.011,0.018,(sx*0.26,0.61,z),rot=(0,math.pi/2,0),material=chrome,body=frame)
# Back pad pivot mounts at lower end.
back_pivot=(0.0,0.84,0.54)
for sx in (-1,1):
    v4.box(f'backrest_hinge_leaf_{sx}',(0.12,0.07,0.06),(sx*0.36,0.83,0.45),bevel=0.008,material=frame_black,body=frame)
    v4.torus(f'backrest_frame_bearing_{sx}',0.043,0.010,(sx*0.34,back_pivot[1],back_pivot[2]),rot=(0,math.pi/2,0),material=chrome,body=frame)
    v4.rod(f'backrest_frame_bearing_brace_{sx}',(sx*0.36,0.80,0.48),(sx*0.34,0.81,0.50),0.010,material=frame_black,body=frame)
    v4.rod(f'backrest_frame_leaf_tie_{sx}',(sx*0.30,0.83,0.45),(sx*0.25,0.83,0.45),0.018,material=frame_black,body=frame)
    v4.cylinder(f'backrest_hinge_pin_{sx}',0.025,0.19,(sx*0.36,back_pivot[1],back_pivot[2]),rot=(0,math.pi/2,0),material=chrome,body=frame)
# Catch pivot pins, positioned beside the rails.
catch_t=0.84
catch_center=tuple(rail_start[i]+d[i]*catch_t for i in range(3))
for sx in (-1,1):
    x=sx*0.62
    v4.rod(f'catch_pivot_bridge_{sx}',(sx*0.49,catch_center[1],catch_center[2]),(x,catch_center[1],catch_center[2]),0.045,square=True,bevel=0.004,material=frame_black,body=frame)
    v4.cylinder(f'catch_pivot_pin_{sx}',0.018,0.19,(sx*0.555,catch_center[1],catch_center[2]),rot=(0,math.pi/2,0),material=chrome,body=frame)
    v4.cylinder(f'catch_bridge_bolt_{sx}',0.014,0.012,(sx*0.50,catch_center[1],catch_center[2]+0.035),rot=(0,math.pi/2,0),material=chrome,body=frame)
# Branding and caution mark on the outside of right upright.
for sx in (-1,1):
    # Two unloaded storage pegs welded to the rear uprights.
    for z in (0.38,0.66):
        v4.cylinder(f'frame_storage_horn_{sx}_{z}',0.026,0.27,(sx*0.73,0.79,z),rot=(0,math.pi/2,0),material=steel,body=frame)
        v4.cylinder(f'frame_storage_horn_end_{sx}_{z}',0.032,0.018,(sx*0.875,0.79,z),rot=(0,math.pi/2,0),material=black,body=frame)
        v4.torus(f'frame_storage_horn_weld_{sx}_{z}',0.034,0.006,(sx*0.61,0.79,z),rot=(0,math.pi/2,0),material=chrome,body=frame)
    # Recessed brand / warning plaques on the outside of the uprights.
    v4.box(f'frame_id_badge_{sx}',(0.012,0.19,0.10),(sx*0.615,0.69,1.16),bevel=0.012,material=black,body=frame)
    v4.box(f'frame_id_accent_{sx}',(0.014,0.12,0.012),(sx*0.623,0.69,1.19),bevel=0.003,material=warning,body=frame)

# Sled carriage at mid rail travel. All load and footplate parts travel together.
sled = v4.body('sled')
t_rest=1.02
center=tuple(rail_start[i]+d[i]*t_rest for i in range(3))
# Two side bearing trucks and central cross tube.
for sx in (-1,1):
    x=sx*0.49
    # bearing block straddles each round rail; roller axles are transverse.
    v4.box(f'bearing_truck_{sx}',(0.22,0.28,0.12),(x,center[1],center[2]),rot=(-math.pi/4,0,0),bevel=0.025,material=black,body=sled)
    for offset in (-0.085,0.085):
        yy=center[1]+d[1]*offset; zz=center[2]+d[2]*offset
        v4.cylinder(f'roller_{sx}_{offset}',0.068,0.14,(x,yy,zz),rot=(0,math.pi/2,0),material=rubber,body=sled)
        # Outboard machined bearing rings visibly encircle each guide rod.
        v4.torus(f'linear_bearing_race_{sx}_{offset}',0.050,0.012,(sx*0.635,yy,zz),rot=(math.pi/4,0,0),material=steel,body=sled)
        v4.torus(f'linear_bearing_seal_{sx}_{offset}',0.036,0.006,(sx*0.65,yy,zz),rot=(math.pi/4,0,0),material=rubber,body=sled)
    # Retainer plates tie the bearing races into the carriage cheek.
    v4.box(f'bearing_cover_{sx}',(0.026,0.31,0.15),(sx*0.61,center[1],center[2]),rot=(-math.pi/4,0,0),bevel=0.014,material=frame_black,body=sled)
    for offset in (-0.12,0.12):
        yy=center[1]+d[1]*offset; zz=center[2]+d[2]*offset
        v4.cylinder(f'bearing_cover_bolt_{sx}_{offset}',0.014,0.012,(sx*0.63,yy,zz),rot=(0,math.pi/2,0),material=chrome,body=sled)
v4.rod('sled_crossbar',(-0.92,center[1],center[2]),(0.92,center[1],center[2]),0.055,material=frame_black,body=sled)
# Footplate projects uphill from carriage, facing back toward the user.
plate_c=tuple(center[i]+d[i]*0.42 for i in range(3))
plate_rot=(math.pi/4,0,0)
v4.box('footplate_shell',(0.84,0.56,0.065),plate_c,rot=plate_rot,bevel=0.03,material=platform,body=sled)
# Rubber traction field and spaced ribs; local plate Y maps down/up its face.
v4.box('footplate_grip_field',(0.72,0.43,0.018),(plate_c[0],plate_c[1]-d[1]*0.041,plate_c[2]-d[2]*0.041),rot=plate_rot,bevel=0.004,material=black,body=sled)
for j in range(7):
    off=-0.18+j*0.06
    q=(plate_c[0],plate_c[1]+side_normal[1]*off-d[1]*0.052,plate_c[2]+side_normal[2]*off-d[2]*0.052)
    v4.box(f'footplate_traction_rib_{j}',(0.68,0.026,0.018),q,rot=plate_rot,bevel=0.008,material=traction,body=sled)
# Outer lip bars around plate face.
for sx in (-1,1):
    v4.box(f'footplate_side_lip_{sx}',(0.04,0.57,0.05),(plate_c[0]+sx*0.405,plate_c[1]-d[1]*0.034,plate_c[2]-d[2]*0.034),rot=plate_rot,bevel=0.009,material=black,body=sled)
# A raised toe-stop at the bottom edge makes the platform read as a formed tray.
v4.box('footplate_bottom_lip',(0.82,0.045,0.052),(plate_c[0],plate_c[1]-side_normal[1]*0.255-d[1]*0.035,plate_c[2]-side_normal[2]*0.255-d[2]*0.035),rot=plate_rot,bevel=0.01,material=black,body=sled)
# Backside stamped ribs stiffen the plate and keep its product finish legible in overhead views.
for j in range(6):
    off=-0.20+j*0.08
    q=(plate_c[0],plate_c[1]+side_normal[1]*off+d[1]*0.042,plate_c[2]+side_normal[2]*off+d[2]*0.042)
    v4.box(f'footplate_back_stiffener_{j}',(0.70,0.018,0.018),q,rot=plate_rot,bevel=0.006,material=frame_black,body=sled)
# Embossed direction marks on the non-contact face.
for sx in (-1,1):
    v4.box(f'footplate_back_mark_{sx}',(0.045,0.20,0.012),(sx*0.31,plate_c[1]+side_normal[1]*0.16+d[1]*0.041,plate_c[2]+side_normal[2]*0.16+d[2]*0.041),rot=plate_rot,bevel=0.006,material=black,body=sled)
# Small fasteners at the four platform corners.
for sx in (-1,1):
    for off in (-0.22,0.22):
        p=(sx*0.365,plate_c[1]+side_normal[1]*off-d[1]*0.048,plate_c[2]+side_normal[2]*off-d[2]*0.048)
        v4.cylinder(f'footplate_fastener_{sx}_{off}',0.012,0.012,p,rot=(math.pi/4,0,0),material=chrome,body=sled)
# Angled gussets carry foot pressure from the carriage crossbar into the plate.
for sx in (-1,1):
    v4.rod(f'footplate_gusset_{sx}',(sx*0.35,center[1],center[2]),(sx*0.35,plate_c[1],plate_c[2]),0.035,square=True,bevel=0.006,material=frame_black,body=sled)
# Four plate-loaded horns, each carries four thick plates and a stop collar.
for sx in (-1,1):
    x=sx*0.85
    horn_start=(x,center[1]+d[1]*0.15,center[2]+d[2]*0.15)
    horn_end=(x,center[1]+d[1]*0.68,center[2]+d[2]*0.68)
    v4.rod(f'weight_horn_{sx}',horn_start,horn_end,0.032,material=chrome,body=sled)
    v4.rod(f'horn_root_brace_{sx}',(x,center[1],center[2]),horn_start,0.045,material=frame_black,body=sled)
    # Three common plate sizes plus a thin change plate, all with a turned hub ring.
    plate_radii=(0.15,0.13,0.105,0.085)
    for k, radius in enumerate(plate_radii):
        t=0.25+k*0.10
        pos=(x,center[1]+d[1]*t,center[2]+d[2]*t)
        v4.cylinder(f'weight_plate_{sx}_{k}',radius,0.065,pos,rot=(math.atan2(-d[1],d[2]),0,0),bevel=0.006,material=black,body=sled)
        for face in (-1,1):
            hub=tuple(pos[i]+d[i]*face*0.034 for i in range(3))
            v4.torus(f'weight_plate_hub_{sx}_{k}_{face}',0.038,0.007,hub,rot=(math.atan2(-d[1],d[2]),0,0),material=steel,body=sled)
    stop=(x,center[1]+d[1]*0.66,center[2]+d[2]*0.66)
    inner=(x,center[1]+d[1]*0.18,center[2]+d[2]*0.18)
    v4.cylinder(f'horn_inner_sleeve_collar_{sx}',0.055,0.03,inner,rot=(math.atan2(-d[1],d[2]),0,0),material=chrome,body=sled)
    v4.cylinder(f'horn_collar_{sx}',0.065,0.035,stop,rot=(math.atan2(-d[1],d[2]),0,0),material=chrome,body=sled)
    endcap=tuple(xyz + d[i]*0.685 for i,xyz in enumerate((x,center[1],center[2])))
    v4.cylinder(f'horn_end_cap_{sx}',0.058,0.04,endcap,rot=(math.atan2(-d[1],d[2]),0,0),material=black,body=sled)
# Sled stop ledges align with raised catch pads.
for sx in (-1,1):
    stop_pos=(sx*0.56,center[1]-d[1]*0.045,center[2]-d[2]*0.045)
    v4.box(f'sled_stop_tab_{sx}',(0.15,0.11,0.075),stop_pos,rot=(-math.pi/4,0,0),bevel=0.014,material=warning,body=sled)
    v4.box(f'sled_stop_wear_pad_{sx}',(0.12,0.052,0.012),(sx*0.56,stop_pos[1]-d[1]*0.01,stop_pos[2]-d[2]*0.01),rot=(-math.pi/4,0,0),bevel=0.006,material=black,body=sled)

# Backrest body; pad is tilted back slightly from vertical and pivots at its lower edge.
back = v4.body('backrest')
back_angle=math.radians(60)
def back_world(x,y,z):
    return (back_pivot[0]+x,
            back_pivot[1]+math.cos(back_angle)*y-math.sin(back_angle)*z,
            back_pivot[2]+math.sin(back_angle)*y+math.cos(back_angle)*z)
# Cushion centered 0.34 m up its local Y axis.
v4.box('backrest_shell',(0.54,0.68,0.075),back_world(0,0.42,0),rot=(back_angle,0,0),bevel=0.045,material=black,body=back)
v4.box('backrest_cushion',(0.51,0.64,0.12),back_world(0,0.42,-0.075),rot=(back_angle,0,0),bevel=0.05,material=padmat,body=back)
# Piping along long cushion edges; slight radius and correctly follow pad plane.
for sx in (-1,1):
    v4.rod(f'backrest_piping_{sx}',back_world(sx*0.246,0.10,-0.087),back_world(sx*0.246,0.74,-0.087),0.006,material=stitch,body=back)
for seam_y in (0.27,0.57):
    v4.rod(f'backrest_cross_stitch_{seam_y}',back_world(-0.22,seam_y,-0.137),back_world(0.22,seam_y,-0.137),0.0035,material=stitch,body=back)
v4.box('backrest_crown_panel',(0.43,0.26,0.012),back_world(0,0.42,-0.139),rot=(back_angle,0,0),bevel=0.045,material=padmat,body=back)
# Hinge eyes and radial arms on the moving backrest clear the frame pin bore.
for sx in (-1,1):
    v4.torus(f'backrest_moving_bushing_{sx}',0.043,0.009,(sx*0.36,back_pivot[1],back_pivot[2]),rot=(0,math.pi/2,0),material=steel,body=back)
    v4.rod(f'backrest_hinge_arm_{sx}',(sx*0.30,back_pivot[1],back_pivot[2]-0.050),(sx*0.36,back_pivot[1],back_pivot[2]-0.050),0.011,material=steel,body=back)
    v4.rod(f'backrest_hinge_brace_{sx}',(sx*0.30,back_pivot[1]+0.02,back_pivot[2]-0.050),(sx*0.36,back_pivot[1]+0.02,back_pivot[2]-0.035),0.0095,material=steel,body=back)
    cheek=back_world(0,0.10,0)
    v4.box(f'backrest_hinge_cheek_{sx}',(0.08,0.035,0.075),(sx*0.30,cheek[1],cheek[2]),rot=(back_angle,0,0),bevel=0.012,material=black,body=back)
    gusset_a=(sx*0.30,back_pivot[1],back_pivot[2]-0.050)
    gusset_b=(sx*0.30,back_pivot[1]+0.035,back_pivot[2]-0.061)
    gusset_c=(sx*0.30,back_pivot[1]+0.078,back_pivot[2]+0.045)
    gusset_d=(sx*0.30,cheek[1],cheek[2])
    v4.rod(f'backrest_shell_hinge_gusset_lower_{sx}',gusset_a,gusset_b,0.012,material=black,body=back)
    v4.rod(f'backrest_shell_hinge_gusset_diagonal_{sx}',gusset_b,gusset_c,0.012,material=black,body=back)
    v4.rod(f'backrest_shell_hinge_gusset_upper_{sx}',gusset_c,gusset_d,0.012,material=black,body=back)
# Two safety catches, each rotates in the YZ plane at the rail side.
for sx, nm in [(-1,'safety_left'),(1,'safety_right')]:
    b=v4.body(nm)
    x=sx*0.62; pivot=(x,catch_center[1],catch_center[2])
    # The ring clears the fixed pin; the 150 mm lever swings its hook into the carriage stop lug.
    v4.torus(f'{nm}_latch_bushing',0.033,0.008,pivot,rot=(0,math.pi/2,0),material=steel,body=b)
    arm_len=0.20
    p_end=(x,pivot[1],pivot[2]+arm_len)
    arm_start=(x,pivot[1],pivot[2]+0.039)
    v4.rod(f'{nm}_latch_arm',arm_start,p_end,0.021,material=red,body=b)
    v4.box(f'{nm}_red_stop_shoe',(0.16,0.15,0.07),p_end,rot=(math.pi/2,0,0),bevel=0.022,material=red,body=b)
    # Hook toe projects beyond the stop face, making the undercut engagement legible.
    hook_tip=(x,p_end[1]-d[1]*0.045,p_end[2]-d[2]*0.045)
    v4.box(f'{nm}_hook_toe',(0.14,0.055,0.055),hook_tip,rot=(math.pi/4,0,0),bevel=0.012,material=red,body=b)
    # A chunky, grippable cross handle sits at the outer end of the lever.
    grip_pos=(x+sx*0.075,pivot[1],pivot[2]+0.105)
    v4.cylinder(f'{nm}_hand_knob',0.035,0.13,grip_pos,rot=(0,math.pi/2,0),material=rubber,body=b)
    for off in (-0.045,0.045):
        v4.torus(f'{nm}_handle_rib_{off}',0.031,0.003,(x+sx*0.075,pivot[1],pivot[2]+0.105+off),rot=(0,math.pi/2,0),material=black,body=b)
    # Cap seats against the outside face of its bracket; the fixed pin passes through the bracket.
    cap_x=sx*0.653
    v4.cylinder(f'{nm}_pivot_cap',0.033,0.05,(cap_x,pivot[1],pivot[2]),rot=(0,math.pi/2,0),material=chrome,body=b)
    lim=(-3*math.pi/4,0)
    v4.joint(f'{nm}_hinge','revolute',frame,b,pivot,axis=(1,0,0),limits=lim)

v4.joint('sled_travel','prismatic',frame,sled,center,axis=d,limits=(-0.35,0.35))
v4.joint('backrest_hinge','revolute',frame,back,origin=back_pivot,axis=(1,0,0),limits=(-0.18,0.32))
v4.save(os.path.join(os.getcwd(),'asset.blend'))
print('saved asset.blend')
