"""Detailed adjustable rehabilitation parallel bars. Run with Blender --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: clinical graphite frame, brushed tube rails, and molded blue controls.
graphite = v4.metal("graphite_powdercoat", color=(0.19, 0.22, 0.25), roughness=0.42, brushed=False)
steel = v4.metal("satin_stainless", color=(0.74, 0.78, 0.80), roughness=0.24, brushed=True)
zinc = v4.metal("zinc_fasteners", color=(0.57, 0.61, 0.64), roughness=0.31, brushed=False)
blue = v4.plastic("medical_blue_polymer", color=(0.045, 0.16, 0.34), roughness=0.32)
blue_light = v4.plastic("blue_grip_rubber", color=(0.075, 0.22, 0.40), roughness=0.56)
rubber = v4.rubber("black_floor_rubber", color=(0.035, 0.04, 0.045), roughness=0.78)
white = v4.plastic("safety_marking", color=(0.88, 0.91, 0.89), roughness=0.48)
accent = v4.plastic("safety_cyan", color=(0.10, 0.55, 0.78), roughness=0.4)

# Main envelope: 2.55 m long x 1.42 m max width x 1.16 m max rail height.
XREST = 0.39
YPOST = 0.78
BEAM_Z = 0.105
RAIL_Z = 0.91

base = v4.body("base_frame")
# Transverse width beams, rectangular closed steel extrusion with softened edges.
for end, y in (("front", -YPOST), ("rear", YPOST)):
    v4.box(f"{end}_width_beam", (1.38, 0.082, 0.070), (0, y, BEAM_Z), bevel=0.012,
           material=graphite, body=base)
    # End caps with visible attachment screws.
    for sx in (-1, 1):
        x = sx * 0.686
        v4.box(f"{end}_beam_endcap_{sx}", (0.018, 0.086, 0.074), (x, y, BEAM_Z), bevel=0.008,
               material=blue, body=base)
        v4.cylinder(f"{end}_endcap_bolt_{sx}", 0.006, 0.003, (x - sx*0.010, y, BEAM_Z),
                    rot=(0, math.pi/2, 0), segments=16, material=zinc, body=base)
# Two longitudinal outer skids close the base perimeter while keeping the gait lane clear.
for sx in (-1, 1):
    v4.box(f"outer_longitudinal_skid_{sx}", (0.070, 1.56, 0.070), (sx*0.700, 0, BEAM_Z),
           bevel=0.010, material=graphite, body=base)
# Four wide adjustable leveling feet seated under the outer beam ends.
for sy, y in ((-1, -YPOST), (1, YPOST)):
    for sx in (-1, 1):
        x = sx * 0.625
        v4.cylinder(f"leveling_stem_{sx}_{sy}", 0.012, 0.070, (x, y, 0.035),
                    material=zinc, body=base)
        v4.cylinder(f"leveling_foot_{sx}_{sy}", 0.052, 0.022, (x, y, 0.011),
                    material=rubber, bevel=0.004, body=base)
        v4.cylinder(f"foot_ferrule_{sx}_{sy}", 0.022, 0.012, (x, y, 0.025),
                    material=graphite, bevel=0.002, body=base)
# Center maker plate on the outward-facing side of the front transverse beam.
v4.box("maker_plate", (0.075, 0.004, 0.036), (0, -0.823, BEAM_Z), bevel=0.004,
       material=blue, body=base)
v4.text("maker_mark", "REHAB", 0.012, loc=(0, -0.8255, BEAM_Z),
        rot=(math.pi/2, 0, 0), material=white, body=base)

# Four carriage assemblies. Each saddle wraps the transverse beam and carries one upright tube.
carriages = {}
uppers = {}
knobs = {}
for side_name, sx in (("left", -1), ("right", 1)):
    x = sx * XREST
    for end_name, y in (("front", -YPOST), ("rear", YPOST)):
        key = f"{side_name}_{end_name}"
        carriage = v4.body(f"post_base_{key}")
        carriages[key] = carriage
        # A two-piece sliding clamp saddle: top cap, lower retainer, and side cheeks around beam.
        v4.box(f"saddle_top_{key}", (0.19, 0.112, 0.018), (x, y, 0.151), bevel=0.005,
               material=graphite, body=carriage)
        v4.box(f"saddle_understrap_{key}", (0.105, 0.094, 0.012), (x, y, 0.061), bevel=0.004,
               material=graphite, body=carriage)
        for yy in (-1, 1):
            v4.box(f"saddle_cheek_{key}_{yy}", (0.14, 0.012, 0.088), (x, y+yy*0.048, 0.111),
                   bevel=0.003, material=graphite, body=carriage)
        # Saddle clamp hardware on the two visible sides.
        for yy in (-1, 1):
            v4.cylinder(f"saddle_washer_{key}_{yy}", 0.010, 0.004, (x, y+yy*0.058, 0.105),
                        rot=(math.pi/2, 0, 0), segments=24, material=zinc, body=carriage)
            v4.cylinder(f"saddle_bolt_{key}_{yy}", 0.006, 0.012, (x, y+yy*0.062, 0.105),
                        rot=(math.pi/2, 0, 0), segments=6, material=zinc, body=carriage)
        # Lower outer post and reinforcing base collar.
        v4.cylinder(f"lower_post_{key}", 0.034, 0.700, (x, y, 0.510), segments=48,
                    material=graphite, bevel=0.004, body=carriage)
        v4.cylinder(f"post_foot_collar_{key}", 0.043, 0.060, (x, y, 0.188),
                    material=steel, bevel=0.004, body=carriage)
        # Top guide collar / wiper sits around the telescoping inner tube.
        v4.cylinder(f"upper_guide_collar_{key}", 0.039, 0.040, (x, y, 0.852),
                    material=steel, bevel=0.003, body=carriage)
        v4.torus(f"guide_wiper_ring_{key}", 0.0265, 0.0022, loc=(x, y, 0.874),
                 material=blue, body=carriage)
        # Height scale panel on the inward-facing side of the outer tube plus etched graduation ticks.
        inward = -sx
        panel_x = x + inward*0.0345
        v4.box(f"height_scale_{key}", (0.003, 0.115, 0.31), (panel_x, y, 0.565), bevel=0.001,
               material=blue, body=carriage)
        for k in range(11):
            z = 0.425 + k*0.028
            length = 0.044 if k % 2 == 0 else 0.025
            v4.box(f"scale_tick_{key}_{k}", (0.0018, length, 0.002),
                   (panel_x+inward*0.0021, y-0.019, z), bevel=0.0004, material=white, body=carriage)
        # Safety yellow index stripe near the lock collar.
        v4.box(f"height_index_{key}", (0.002, 0.064, 0.005),
               (panel_x+inward*0.0022, y, 0.734), bevel=0.001, material=accent, body=carriage)
        # Upper inner post (rest height); it is intentionally inserted into the outer tube.
        upper = v4.body(f"upper_post_{key}")
        uppers[key] = upper
        v4.cylinder(f"inner_tube_{key}", 0.022, 0.297, (x, y, 0.7485), segments=48,
                    material=steel, bevel=0.0025, body=upper)
        # Small bright witness band near the exposed top of the telescoping tube.
        v4.cylinder(f"tube_witness_band_{key}", 0.0232, 0.009, (x, y, 0.884),
                    material=zinc, bevel=0.001, body=upper)
        # Saddle socket below rail, fitted tightly around upper tube.
        v4.cylinder(f"rail_mount_socket_{key}", 0.031, 0.055, (x, y, 0.925),
                    material=graphite, bevel=0.004, body=upper)
        v4.box(f"saddle_tongue_{key}", (0.070, 0.060, 0.018), (x, y, 0.952), bevel=0.005,
               material=graphite, body=upper)
        v4.cylinder(f"saddle_pin_{key}", 0.006, 0.064, (x, y, 0.954), rot=(math.pi/2,0,0),
                    material=zinc, body=upper)
        # Clamp screw collar/stem location is on the outer face of each lower post.
        outward = sx
        knob = v4.body(f"lock_knob_{key}")
        knobs[key] = knob
        kx = x + outward*0.034
        # Threaded stem, hexagonal lock nut and star-wheel hub; wheel plane is YZ.
        v4.cylinder(f"lock_stem_{key}", 0.008, 0.050, (x+outward*0.032, y, 0.690),
                    rot=(0, math.pi/2, 0), segments=24, material=zinc, body=knob)
        v4.cylinder(f"lock_nut_{key}", 0.015, 0.012, (kx+outward*0.012, y, 0.690),
                    rot=(0, math.pi/2, 0), segments=6, material=steel, body=knob)
        wheel_x = kx + outward*0.029
        v4.cylinder(f"star_hub_{key}", 0.019, 0.018, (wheel_x, y, 0.690),
                    rot=(0, math.pi/2, 0), segments=32, material=blue, body=knob)
        # Five radial grips with soft rounded ends make a recognizable hand-turn knob.
        for i in range(5):
            a = 2*math.pi*i/5 + math.pi/2
            yy, zz = y + 0.034*math.cos(a), 0.690 + 0.034*math.sin(a)
            v4.rod(f"star_spoke_{key}_{i}", (wheel_x, y+0.012*math.cos(a), 0.690+0.012*math.sin(a)),
                   (wheel_x, yy, zz), 0.0065, material=blue, body=knob)
            v4.sphere(f"star_lobe_{key}_{i}", 0.011, (wheel_x, yy, zz), segments=24,
                      material=blue_light, body=knob)
        v4.cylinder(f"star_face_{key}", 0.010, 0.003, (wheel_x+outward*0.010, y, 0.690),
                    rot=(0, math.pi/2, 0), segments=32, material=accent, body=knob)
        # Slide origins are placed at the actual rail-beam center and tube engagement point.
        slide_limits = (0.0, -0.12) if sx < 0 else (0.0, 0.12)
        lo, hi = min(slide_limits), max(slide_limits)
        v4.joint(f"width_slide_{key}", "prismatic", base, carriage,
                 origin=(x, y, BEAM_Z), axis=(1,0,0), limits=(lo, hi))
        v4.joint(f"height_slide_{key}", "prismatic", carriage, upper,
                 origin=(x, y, 0.642), axis=(0,0,1), limits=(0.0,0.15))
        v4.joint(f"turn_lock_{key}", "continuous", carriage, knob,
                 origin=(x+outward*0.034, y, 0.690), axis=(1,0,0))

# Two one-piece handrails, each supported by a front tree joint and rear fixed loop closure.
rails = {}
for side_name, sx in (("left", -1), ("right", 1)):
    x = sx * XREST
    rail = v4.body(f"handrail_{side_name}")
    rails[side_name] = rail
    # 42 mm OD satin stainless round rail, 2.38 m end-to-end.
    v4.rod(f"continuous_handrail_{side_name}", (x, -1.19, RAIL_Z), (x, 1.19, RAIL_Z), 0.021,
           segments=48, bevel=0.001, material=steel, body=rail)
    # Rounded blue safety end plugs with polished retaining collars.
    for sy in (-1, 1):
        y = sy*1.19
        v4.sphere(f"rail_end_plug_{side_name}_{sy}", 0.021, (x, y, RAIL_Z), segments=32,
                  material=blue, body=rail)
        v4.torus(f"end_collar_{side_name}_{sy}", 0.021, 0.0024,
                 loc=(x, sy*1.145, RAIL_Z), rot=(math.pi/2,0,0), material=zinc, body=rail)
    # Dark blue non-slip grip zones at the final 22 cm, segmented rings for tactile texture.
    for sy in (-1, 1):
        y0 = sy*0.955
        v4.cylinder(f"grip_sleeve_{side_name}_{sy}", 0.0235, 0.225,
                    (x, sy*1.0675, RAIL_Z), rot=(math.pi/2,0,0), material=blue_light, body=rail)
        for k in range(8):
            yy = y0 + sy*k*0.027
            v4.torus(f"grip_ridge_{side_name}_{sy}_{k}", 0.0232, 0.0011,
                     loc=(x, yy, RAIL_Z), rot=(math.pi/2,0,0), material=blue, body=rail)
    # Two precision saddle bands at the support points.
    for end_name, y in (("front", -YPOST), ("rear", YPOST)):
        v4.torus(f"rail_saddle_band_{side_name}_{end_name}", 0.022, 0.003,
                 loc=(x, y, RAIL_Z), rot=(math.pi/2,0,0), material=graphite, body=rail)
        v4.box(f"rail_saddle_plate_{side_name}_{end_name}", (0.060, 0.060, 0.012),
               (x, y, RAIL_Z-0.022), bevel=0.004, material=graphite, body=rail)
    # Attach rail to front upper post as tree edge, and to rear upper post as fixed physical loop.
    v4.joint(f"rail_mount_{side_name}_front", "fixed", uppers[f"{side_name}_front"], rail,
             origin=(x, -YPOST, RAIL_Z), axis=(0,0,1))
    v4.joint(f"rail_support_{side_name}_rear", "fixed", uppers[f"{side_name}_rear"], rail,
             origin=(x, YPOST, RAIL_Z), axis=(0,0,1))

# Save at the physically useful neutral width and minimum working height.
v4.save(os.path.join(os.getcwd(), "asset.blend"))
print("saved asset.blend")
