import math
import os
import sys
from mathutils import Vector

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

v4.reset()

# Moulded white seat, satin steel frame, and dark tactile grips.
white = v4.plastic("warm_white_medical_polymer", (0.91, 0.90, 0.86), roughness=0.36, texture=0.10)
white_detail = v4.plastic("soft_white_detail", (0.84, 0.84, 0.80), roughness=0.43, texture=0.08)
steel = v4.metal("satin_stainless", color=(0.72, 0.74, 0.75), roughness=0.31, brushed=True)
steel_dark = v4.metal("darkened_hinge_steel", color=(0.43, 0.46, 0.48), roughness=0.38, brushed=False)
rubber = v4.rubber("charcoal_non_slip", color=(0.075, 0.083, 0.085), roughness=0.82)
ink = v4.mat("subtle_silver_marking", (0.62, 0.64, 0.62), roughness=0.6)

frame = v4.body("frame")

# Oval annular seat shell: elliptical plan, gently crowned, with inner and outer rounded edges.
def annular_shell(name, outer=(0.218, 0.222), inner=(0.105, 0.137), z0=0.442, z1=0.475, n=96, body=None, material=None):
    verts, faces = [], []
    # A five-loop cross section gives the molded rim a tapered underside,
    # crowned sitting surface, and a broadened anterior hygiene recess.
    loops = ((outer[0]-0.005, outer[1]-0.005, z0, "outer_bottom"),
             (outer[0], outer[1], z1, "outer_top"),
             ((outer[0]+inner[0])*0.5, (outer[1]+inner[1])*0.5, z1+0.008, "crown"),
             (inner[0], inner[1], z1+0.003, "inner_top"),
             (inner[0]-0.006, inner[1]-0.006, z0, "inner_bottom"))
    for rx, ry, z, edge in loops:
        for i in range(n):
            a = 2 * math.pi * i / n
            if edge == "inner_top":
                rx_a = rx + 0.020 * max(0.0, -math.sin(a)) ** 10
            else:
                rx_a = rx
            contour = 0.0012 * (1.0 - math.cos(2*a)) * 0.5 if edge in ("outer_top", "crown", "inner_top") else 0.0
            verts.append((rx_a * math.cos(a), ry * math.sin(a), z + contour))
    ob, ot, mt, it, ib = 0, n, 2*n, 3*n, 4*n
    for i in range(n):
        j = (i + 1) % n
        # Two crowned annular top panels, underside, and rounded perimeter walls.
        faces.append((ot+i, ot+j, mt+j, mt+i))
        faces.append((mt+i, mt+j, it+j, it+i))
        faces.append((ob+j, ob+i, ib+i, ib+j))
        faces.append((ob+i, ob+j, ot+j, ot+i))
        faces.append((ib+j, ib+i, it+i, it+j))
    mesh = bpy.data.meshes.new(name + "Mesh")
    mesh.from_pydata(verts, [], faces)
    mesh.materials.append(material)
    mesh.update()
    obj = bpy.data.objects.new(name, mesh)
    v4._link(obj)
    bevel = obj.modifiers.new("Soft moulded perimeter", "BEVEL")
    bevel.width = 0.008
    bevel.segments = 4
    bevel.limit_method = "ANGLE"
    bevel.angle_limit = math.radians(25)
    obj.modifiers.new("Weighted mould normals", "WEIGHTED_NORMAL")
    for poly in mesh.polygons:
        poly.use_smooth = True
    if body is not None: v4.part(obj, body)
    return obj

import bpy
annular_shell("one_piece_contoured_seat_ring", body=frame, material=white)
# A deep molded skirt wraps the load-bearing frame at all four seat mounts.
annular_shell("integral_underseat_molded_skirt", outer=(0.215, 0.219), inner=(0.120, 0.140),
              z0=0.409, z1=0.445, n=96, body=frame, material=white_detail)
# Slightly raised oval front apron / splash guard, blended visually into the forward rim.
v4.box("front_splash_guard", (0.125, 0.012, 0.040), (0, -0.145, 0.492),
       bevel=0.010, material=white, body=frame)
# Under-seat reinforcing ribs run from the shell's inside edge to the outside edge.
for sx in (-1, 1):
    v4.rod(f"underside_reinforcement_{sx}", (sx*0.095, -0.105, 0.432), (sx*0.175, -0.105, 0.432),
           0.009, square=True, material=white_detail, body=frame)

# Four tubular legs, welded cross rails, moulded collars and rubber feet.
leg_x, leg_y = 0.155, 0.145

def hollow_socket(name, x, y, zlo, zhi, ro, ri, body, material, n=32):
    """Hollow steel sleeve with open bore for a sliding inner tube."""
    verts, faces = [], []
    loops = ((ro, zlo), (ro, zhi), (ri, zlo), (ri, zhi))
    for radius, z in loops:
        for i in range(n):
            a = 2 * math.pi * i / n
            verts.append((x + radius*math.cos(a), y + radius*math.sin(a), z))
    ob, ot, ib, it = 0, n, 2*n, 3*n
    for i in range(n):
        j = (i+1) % n
        faces.extend(((ob+i, ob+j, ot+j, ot+i), (ib+j, ib+i, it+i, it+j),
                      (ob+j, ob+i, ib+i, ib+j), (ot+i, ot+j, it+j, it+i)))
    me = bpy.data.meshes.new(name + "Mesh")
    me.from_pydata(verts, [], faces)
    me.materials.append(material)
    me.update()
    obj = bpy.data.objects.new(name, me)
    v4._link(obj)
    bevel = obj.modifiers.new("Rolled sleeve lips", "BEVEL")
    bevel.width = 0.0012
    bevel.segments = 2
    obj.modifiers.new("Sleeve normals", "WEIGHTED_NORMAL")
    v4.part(obj, body)
    return obj

for sx in (-1, 1):
    for sy in (-1, 1):
        x, y = sx*leg_x, sy*leg_y
        # Broad upper collar seats flush against the underside of the riser.
        v4.cylinder(f"leg_socket_collar_{sx}_{sy}", 0.023, 0.035, (x, y, 0.430),
                    material=white_detail, body=frame)
        # Molded saddle wraps the sleeve as it enters the underside skirt.
        v4.box(f"seat_leg_wrap_saddle_{sx}_{sy}", (0.070, 0.064, 0.045),
               (x, y, 0.421), bevel=0.018, material=white, body=frame)
        hollow_socket(f"outer_leg_socket_{sx}_{sy}", x, y, 0.155, 0.425, 0.014, 0.011, frame, steel)
        # Rolled collar at the top of each sleeve and a lower index ring.
        v4.torus(f"socket_top_lock_collar_{sx}_{sy}", 0.0142, 0.0022, (x, y, 0.414),
                 material=steel_dark, body=frame)
        v4.torus(f"socket_index_band_{sx}_{sy}", 0.0141, 0.0014, (x, y, 0.175),
                 material=steel_dark, body=frame)
        for k, z in enumerate((0.205, 0.265, 0.295)):
            # Dark shallow index holes show the discrete telescoping adjustment.
            v4.cylinder(f"socket_adjust_hole_{sx}_{sy}_{k}", 0.0045, 0.002,
                        (x, y - sy*0.014, z), rot=(math.pi/2, 0, 0),
                        segments=20, material=steel_dark, body=frame)
        side_name = "left" if sx < 0 else "right"
        depth_name = "front" if sy < 0 else "rear"
        v4.cylinder(f"{side_name}_{depth_name}_detent_seat", 0.0085, 0.004,
                    (x, y - sy*0.014, 0.235), rot=(math.pi/2, 0, 0),
                    material=steel_dark, body=frame)
        v4.cylinder(f"{side_name}_{depth_name}_spring_button", 0.0052, 0.008,
                    (x, y - sy*0.017, 0.235), rot=(math.pi/2, 0, 0),
                    material=white_detail, body=frame)

# Cross rails make the undercarriage read as a rigid four-leg safety frame.
for sy in (-1, 1):
    y = sy*0.177
    v4.rod(f"transverse_underseat_rail_{sy}", (-leg_x, y, 0.392), (leg_x, y, 0.392),
           0.0105, material=steel, body=frame)
    for sx in (-1, 1):
        v4.cylinder(f"transverse_rail_end_cap_{sx}_{sy}", 0.0105, 0.003,
                    (sx*leg_x, y, 0.392), rot=(0, math.pi/2, 0),
                    material=steel_dark, body=frame)
for sx in (-1, 1):
    x = sx*leg_x
    v4.rod(f"longitudinal_underseat_rail_{sx}", (x, -leg_y, 0.392), (x, leg_y, 0.392),
           0.009, material=steel, body=frame)
    for sy in (-1, 1):
        v4.cylinder(f"longitudinal_rail_end_cap_{sx}_{sy}", 0.009, 0.003,
                    (x, sy*leg_y, 0.392), rot=(math.pi/2, 0, 0),
                    material=steel_dark, body=frame)
# Four broad gusset pads blend legs into cross rails.
for sx in (-1, 1):
    for sy in (-1, 1):
        v4.cylinder(f"upper_leg_mount_pad_{sx}_{sy}", 0.025, 0.012,
                    (sx*leg_x, sy*leg_y, 0.404), material=steel_dark, body=frame)

# Raised side rails carry the flip-up hinge blocks and their resting front sockets.
for sx in (-1, 1):
    v4.rod(f"armrest_side_rail_{sx}", (sx*0.19, -0.145, 0.442), (sx*0.19, 0.145, 0.442),
           0.010, material=steel, body=frame)
    for sy in (-1, 1):
        v4.cylinder(f"seat_rail_mount_bolt_{sx}_{sy}", 0.0045, 0.002,
                    (sx*0.19, sy*0.105, 0.454), segments=20,
                    material=steel_dark, body=frame)
    # Rail end caps, plus a diagonal mount gusset that ties it into the leg frame.
    for sy in (-1, 1):
        v4.cylinder(f"side_rail_end_cap_{sx}_{sy}", 0.0105, 0.003,
                    (sx*0.19, sy*0.145, 0.442), rot=(math.pi/2, 0, 0),
                    material=steel_dark, body=frame)
        v4.rod(f"side_rail_leg_gusset_{sx}_{sy}", (sx*leg_x, sy*leg_y, 0.392),
               (sx*0.19, sy*0.145, 0.442), 0.009, material=steel, body=frame)

# Four hollow outer sleeves stay on the frame; inner tubes and feet slide together.
for sx in (-1, 1):
    for sy in (-1, 1):
        x, y = sx*leg_x, sy*leg_y
        side_name = "left" if sx < 0 else "right"
        depth_name = "front" if sy < 0 else "rear"
        ext = v4.body(f"leg_extension_{side_name}_{depth_name}")
        v4.cylinder(f"telescoping_inner_tube_{sx}_{sy}", 0.0095, 0.230, (x, y, 0.128),
                    material=steel, body=ext)
        v4.cylinder(f"extension_ferrule_{sx}_{sy}", 0.0115, 0.022, (x, y, 0.045),
                    material=steel_dark, body=ext)
        v4.cylinder(f"telescoping_rubber_foot_{sx}_{sy}", 0.022, 0.044, (x, y, 0.022),
                    material=rubber, body=ext)
        # Moulded concentric tread rings on the floor-contacting foot.
        for z in (0.010, 0.020, 0.030):
            v4.torus(f"foot_tread_{sx}_{sy}_{z}", 0.0215, 0.0012, (x, y, z),
                     material=rubber, body=ext)
        v4.joint(f"leg_extension_slide_{side_name}_{depth_name}", "prismatic", frame, ext,
                 origin=(x, y, 0.243), axis=(0, 0, 1), limits=(0.0, 0.08))

# Four visible pan-head bolts fasten the seat shell to the underframe.
for sx in (-1, 1):
    for sy in (-1, 1):
        v4.cylinder(f"seat_frame_bolt_{sx}_{sy}", 0.006, 0.004,
                    (sx*0.145, sy*0.13, 0.476), segments=24,
                    material=steel_dark, body=frame)

# Arm assemblies: close to the rim. The front post rests in a frame socket in the
# lowered position; the entire U-shaped arm swings clear when folded up.
for side, sx in (("left", -1), ("right", 1)):
    arm = v4.body(f"arm_{side}")
    pivot = (sx*0.225, 0.13, 0.535)
    outer_x = sx*0.236
    # Padded grip, rounded end plugs and understated shallow grip ribs.
    v4.rod(f"{side}_arm_padded_grip", (outer_x, -0.205, 0.692), (outer_x, 0.132, 0.692),
           0.019, material=rubber, body=arm)
    for y in (-0.174, -0.146, -0.118, -0.090, -0.062, -0.034):
        v4.torus(f"{side}_grip_rib_{y}", 0.0191, 0.0013, (outer_x, y, 0.692),
                 rot=(math.pi/2, 0, 0), segments=32, ring_segments=10, material=steel_dark, body=arm)
    # Two compact stainless stays tie the arm rail into its hinged side plate.
    v4.rod(f"{side}_rear_arm_web", (outer_x, 0.13, 0.552), (outer_x, 0.13, 0.674),
           0.008, square=True, material=steel, body=arm)
    v4.rod(f"{side}_front_arm_web", (outer_x, -0.125, 0.466), (outer_x, -0.125, 0.674),
           0.009, square=True, material=steel, body=arm)
    v4.rod(f"{side}_lower_arm_tie", (outer_x, -0.125, 0.500), (outer_x, 0.13, 0.535),
           0.007, material=steel, body=arm)
    # Hinge knuckles and pin share the pivot line; outer bracket is attached to the frame.
    v4.rod(f"{side}_hinge_to_rear_web", pivot, (outer_x, 0.13, 0.558),
           0.007, material=steel, body=arm)
    # The pin and knuckle run on the X hinge axis, with the fixed bracket ending
    # just before the moving knuckle so the arm can swing without scraping it.
    v4.cylinder(f"{side}_hinge_knuckle", 0.012, 0.020, pivot,
                rot=(0, math.pi/2, 0), material=steel_dark, body=arm)
    v4.cylinder(f"{side}_hinge_pin_cap", 0.008, 0.003, (pivot[0]+sx*0.012, pivot[1], pivot[2]),
                rot=(0, math.pi/2, 0), material=steel, body=arm)
    v4.box(f"{side}_frame_hinge_bracket", (0.060, 0.058, 0.060),
           (sx*0.185, 0.13, 0.493), bevel=0.015, material=steel, body=frame)
    # Twin clevis ears flank the pin line and are welded into the softened base block.
    for k, ey in enumerate((0.096, 0.164)):
        v4.box(f"{side}_hinge_clevis_ear_{k}", (0.024, 0.020, 0.043),
               (sx*0.203, ey, 0.535), bevel=0.005, material=steel, body=frame)
    v4.rod(f"{side}_hinge_load_stay", (sx*0.155, 0.13, 0.392), (sx*0.190, 0.13, 0.470),
           0.012, material=steel, body=frame)
    v4.cylinder(f"{side}_hinge_washer", 0.014, 0.006, (sx*0.212, 0.13, pivot[2]),
                rot=(0, math.pi/2, 0), material=steel, body=frame)
    # Rounded, spring-loaded hinge release button on the outboard face.
    v4.cylinder(f"{side}_hinge_release_stem", 0.0045, 0.024,
                (sx*0.185, 0.13, 0.535), material=steel_dark, body=frame)
    v4.cylinder(f"{side}_hinge_release_button", 0.0095, 0.008,
                (sx*0.185, 0.13, 0.549), material=white_detail, body=frame)
    # The front support lands on this broad socket at rest, distributing the load
    # onto the same side rail that sits directly over the leg pair.
    v4.rod(f"{side}_front_socket_rail_tab", (sx*0.19, -0.125, 0.442),
           (sx*0.2185, -0.125, 0.448), 0.008, material=steel, body=frame)
    v4.box(f"{side}_front_support_socket", (0.035, 0.046, 0.018),
           (sx*0.236, -0.125, 0.457), bevel=0.005, material=steel_dark, body=frame)
    v4.cylinder(f"{side}_front_socket_bushing", 0.010, 0.006,
                (sx*0.236, -0.125, 0.467), material=white_detail, body=frame)
    # This body has one load-bearing hinge; side webs are part of the moving arm assembly.
    v4.joint(f"{side}_arm_hinge", "revolute", frame, arm,
             origin=pivot, axis=(1, 0, 0), limits=(-math.radians(100), 0))

# Two underside bowl hooks and independent threaded grip knobs. The absent toilet
# bowl is the mating surface; the pads are positioned to bear on its rim underside.
for side, sx in (("left", -1), ("right", 1)):
    x = sx*0.105
    # Paired side cheeks and a soft-faced lower jaw form a sturdy bowl bracket.
    for dx in (-0.020, 0.020):
        v4.rod(f"{side}_bowl_bracket_cheek_{dx}", (x+dx, 0.145, 0.438),
               (x+dx, 0.185, 0.330), 0.0065, material=steel, body=frame)
        v4.rod(f"{side}_bowl_bracket_return_{dx}", (x+dx, 0.185, 0.330),
               (x+dx, 0.145, 0.330), 0.0065, material=steel, body=frame)
    v4.rod(f"{side}_bowl_jaw_crossbar", (x-0.020, 0.145, 0.330),
           (x+0.020, 0.145, 0.330), 0.009, material=steel, body=frame)
    v4.box(f"{side}_bowl_jaw_pad", (0.045, 0.022, 0.012), (x, 0.145, 0.322),
           bevel=0.004, material=rubber, body=frame)
    clamp = v4.body(f"clamp_knob_{side}")
    # The screw rotates in the bracket gap; a broad scalloped handwheel turns it.
    v4.rod(f"{side}_clamp_screw", (x, 0.136, 0.375), (x, 0.223, 0.375),
           0.0055, material=steel_dark, body=clamp)
    # Helical crest makes the threaded engagement legible in close views.
    thread_points = []
    for i in range(181):
        t = i / 180.0
        a = 2 * math.pi * 8 * t
        thread_points.append((x + 0.0064*math.cos(a), 0.150 + 0.064*t,
                              0.375 + 0.0064*math.sin(a)))
    v4.tube(f"{side}_clamp_thread_crest", thread_points, 0.0014,
            material=steel, body=clamp, resolution=24)
    v4.cylinder(f"{side}_clamp_pressure_tip", 0.014, 0.010, (x, 0.132, 0.375),
                rot=(math.pi/2, 0, 0), material=rubber, body=clamp)
    v4.lathe(f"{side}_clamp_handwheel", [(0, 0), (0.011, 0), (0.016, 0.004),
             (0.019, 0.010), (0.017, 0.016), (0.010, 0.020), (0, 0.020)],
             loc=(x, 0.224, 0.375), rot=(math.pi/2, 0, 0),
             material=rubber, body=clamp)
    v4.cylinder(f"{side}_handwheel_hub", 0.008, 0.006, (x, 0.227, 0.375),
                rot=(math.pi/2, 0, 0), material=steel, body=clamp)
    for k, y_rib in enumerate((0.207, 0.216)):
        v4.torus(f"{side}_handwheel_grip_rib_{k}", 0.0175, 0.0012,
                 (x, y_rib, 0.375), rot=(math.pi/2, 0, 0),
                 material=steel_dark, body=clamp)
    v4.joint(f"{side}_clamp_rotation", "continuous", frame, clamp,
             origin=(x, 0.224, 0.375), axis=(0, 1, 0))

# Discreet rear molded seam/registration marks.
for sx in (-1, 1):
    v4.cylinder(f"rear_registration_dot_{sx}", 0.0025, 0.0015,
                (sx*0.08, 0.203, 0.476), rot=(math.pi/2, 0, 0), segments=16,
                material=ink, body=frame)

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