"""Detailed residential glider chair with a closed four-bar seat suspension."""
import math
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import v4lib as v4

v4.reset()

# Materials
walnut = v4.wood("warm_walnut", light=(0.52, 0.32, 0.18), dark=(0.27, 0.14, 0.075), grain_scale=5)
walnut_edge = v4.wood("walnut_endgrain", light=(0.46, 0.27, 0.14), dark=(0.23, 0.12, 0.06), grain_scale=9)
steel = v4.metal("satin_nickel_steel", color=(0.48, 0.51, 0.53), roughness=0.28, brushed=True)
chrome = v4.metal("pivot_zinc", color=(0.68, 0.70, 0.71), roughness=0.28, brushed=False)
upholstery = v4.fabric("oatmeal_twill", (0.61, 0.54, 0.42))
piping = v4.fabric("dark_welt", (0.30, 0.24, 0.17))
underside = v4.fabric("seat_deck_cloth", (0.27, 0.25, 0.21))
rubber = v4.rubber("floor_glides")

# Dimensions / pivot coordinates. Front is -Y.
BASE_X = 0.315
LINK_X = 0.355
Y_FRONT = -0.205
Y_REAR = 0.175
Z_BASE_PIVOT = 0.500
Z_SEAT_PIVOT = 0.300
SEAT_DROP = 0.145
Y_SHIFT = 0.000
Y_SF = Y_FRONT + Y_SHIFT
Y_SR = Y_REAR + Y_SHIFT
LINK_LENGTH = math.sqrt((Z_SEAT_PIVOT-Z_BASE_PIVOT)**2 + Y_SHIFT**2)

base = v4.body("base")
front_links = v4.body("front_links")
rear_links = v4.body("rear_links")
seat = v4.body("seat_assembly")

# Fixed hardwood base: two long side rails, shaped cross rails, feet and metal pivot towers.
# Side rails are rounded rectangular hardwood members with softened end blocks.
for sx in (-1, 1):
    x = sx * BASE_X
    v4.box(f"base_side_rail_{sx}", (0.072, 0.82, 0.085), (x, 0.0, 0.135), bevel=0.018, material=walnut, body=base)
    # Dark inset apron strip on the outer face of each side rail.
    v4.box(f"rail_inlay_{sx}", (0.002, 0.54, 0.012), (sx*(BASE_X+0.037), 0.0, 0.145), bevel=0.005, material=walnut_edge, body=base)
    # Short walnut feet bridge the rail underside to rubber floor glides.
    for sy in (-1, 1):
        fy = sy*0.345
        v4.box(f"base_foot_{sx}_{sy}", (0.060, 0.070, 0.069), (x, fy, 0.058), bevel=0.012,
               material=walnut, body=base)
        v4.lathe(f"foot_glide_{sx}_{sy}", [(0,0), (0.024,0), (0.024,0.008), (0.020,0.014), (0,0.014)],
                 loc=(x, fy, 0.010), material=rubber, body=base)
# Crossmembers join side rails under the linkage area; rear/front rails are walnut.
for y in (-0.365, 0.365):
    v4.box(f"base_cross_rail_{y}", (0.88, 0.065, 0.075), (0, y, 0.137), bevel=0.014, material=walnut, body=base)
# Subtle inset shoulders on crossmembers create a finished furniture profile.
for y in (-0.365, 0.365):
    v4.box(f"cross_rail_cap_{y}", (0.70, 0.004, 0.012), (0, y-0.034, 0.151), bevel=0.004, material=walnut_edge, body=base)

# Paired sculpted side frames: a continuous bowed rail on each side joins the feet,
# high pivot seats and a curved top stretcher. The section is slimmer than the armrests.
for sx in (-1, 1):
    x = sx * 0.405
    v4.tube(f"curved_glider_side_frame_{sx}",
            [(x,-0.365,0.155), (x,-0.315,0.285), (x,-0.255,0.425),
             (x,Y_FRONT,0.500), (x,-0.135,0.515), (x,-0.015,0.520),
             (x,0.105,0.515), (x,Y_REAR,0.500), (x,0.255,0.425), (x,0.315,0.285), (x,0.365,0.155)],
            0.015, material=walnut_edge, body=base)
    # Bushings span the small gap between each metal link eye and its curved wooden frame.
    for tag, y in (("front",Y_FRONT), ("rear",Y_REAR)):
        v4.cylinder(f"{tag}_outer_bushing_{sx}", 0.019, 0.024,
                    (sx*0.383,y,Z_BASE_PIVOT), rot=(0,math.pi/2,0), material=chrome, body=base)
        v4.cylinder(f"{tag}_bushing_flange_{sx}", 0.024, 0.006,
                    (sx*0.423,y,Z_BASE_PIVOT), rot=(0,math.pi/2,0), material=chrome, body=base)

# Seat suspension: paired steel links joined by a rigid transverse cross-tie per body.
# Each body includes its left/right plates, tie bar and pivot bosses.
for body, tag, y0, y1 in ((front_links, "front", Y_FRONT, Y_SF), (rear_links, "rear", Y_REAR, Y_SR)):
    for sx in (-1, 1):
        x = sx * LINK_X
        v4.rod(f"{tag}_suspension_arm_{sx}", (x, y0, Z_BASE_PIVOT), (x, y1, Z_SEAT_PIVOT), 0.017,
               square=True, bevel=0.003, material=steel, body=body)
        # Reinforced eye bosses around each pin end.
        for label, y, z in (("lower", y0, Z_BASE_PIVOT), ("upper", y1, Z_SEAT_PIVOT)):
            v4.cylinder(f"{tag}_{label}_eye_{sx}", 0.024, 0.030, (x, y, z), rot=(0, math.pi/2, 0),
                        material=chrome, body=body)
    # Low transverse axle at the seat-end eyes ties each left/right pair together
    # while staying below the seat frame and cushion.
    v4.rod(f"{tag}_cross_tie", (-LINK_X, y1, Z_SEAT_PIVOT-0.018),
           (LINK_X, y1, Z_SEAT_PIVOT-0.018), 0.010, material=steel, body=body)

# Seat frame and upholstered seat, all one rigid body. Underside panel sits directly over brackets.
v4.box("seat_frame", (0.650, 0.585, 0.055), (0, -0.005, 0.474), bevel=0.018, material=walnut_edge, body=seat)
# Deep side aprons tie the seat pan, arms and upper linkage brackets into one furniture frame.
for sx in (-1, 1):
    v4.box(f"seat_side_apron_{sx}", (0.054,0.535,0.092), (sx*0.300,-0.005,0.480),
           bevel=0.014, material=walnut, body=seat)
    v4.box(f"apron_inlay_{sx}", (0.002,0.390,0.008), (sx*0.328,-0.005,0.475),
           bevel=0.003, material=walnut_edge, body=seat)
v4.box("seat_underside_panel", (0.605, 0.535, 0.008), (0, -0.005, 0.505), bevel=0.006, material=underside, body=seat)
v4.box("seat_cushion", (0.646, 0.575, 0.105), (0, -0.012, 0.557), bevel=0.045, material=upholstery, body=seat)
# Welt piping around the cushion perimeter, laid on the side near its top seam.
v4.tube("seat_welt", [(-0.276,-0.247,0.575), (0.276,-0.247,0.575), (0.302,-0.221,0.575),
                       (0.302,0.197,0.575), (0.276,0.223,0.575), (-0.276,0.223,0.575),
                       (-0.302,0.197,0.575), (-0.302,-0.221,0.575)], 0.003, material=piping, body=seat, cyclic=True)
# Subtle top panel seam, following the front and side inset.
v4.tube("seat_top_stitch", [(-0.245,-0.245,0.597), (0.245,-0.245,0.597), (0.265,-0.225,0.597),
                             (0.265,0.180,0.597), (0.245,0.200,0.597), (-0.245,0.200,0.597),
                             (-0.265,0.180,0.597), (-0.265,-0.225,0.597)], 0.0014, material=piping, body=seat, cyclic=True)

# Upholstered back, gently reclined toward the rear. Rounded padding plus a tailored inset panel.
BACK_ANGLE = -math.radians(8)
v4.box("backrest_shell", (0.650, 0.090, 0.505), (0, 0.225, 0.823), rot=(BACK_ANGLE,0,0), bevel=0.045,
       material=upholstery, body=seat)
v4.box("backrest_lower_pad", (0.604, 0.045, 0.125), (0, 0.188, 0.665), rot=(BACK_ANGLE,0,0), bevel=0.022,
       material=upholstery, body=seat)
# Raised vertical lumbar seam and two tailored horizontal seams on back face.
# Three softly crowned back pads create tailored panels and visible upholstery breaks.
for idx, xlocal in enumerate((-0.202, 0.0, 0.202)):
    local_y, zrel = -0.057, -0.005
    py = 0.225 + math.cos(BACK_ANGLE)*local_y - math.sin(BACK_ANGLE)*zrel
    pz = 0.823 + math.sin(BACK_ANGLE)*local_y + math.cos(BACK_ANGLE)*zrel
    v4.box(f"back_cushion_panel_{idx}", (0.194,0.026,0.407), (xlocal,py,pz),
           rot=(BACK_ANGLE,0,0), bevel=0.027, material=upholstery, body=seat)
    # Fabric-covered tuft buttons are slightly sunk into each panel face.
    for j, dz in enumerate((-0.105,0.105)):
        local_y_button, zbutton = -0.074, zrel+dz
        by = 0.225 + math.cos(BACK_ANGLE)*local_y_button - math.sin(BACK_ANGLE)*zbutton
        bz = 0.823 + math.sin(BACK_ANGLE)*local_y_button + math.cos(BACK_ANGLE)*zbutton
        v4.sphere(f"back_tuft_{idx}_{j}", 0.008, (xlocal,by,bz), material=piping, body=seat)
# Exposed walnut back stiles follow the reclined edges of the padded back.
for sx in (-1,1):
    v4.rod(f"back_frame_stile_{sx}", (sx*0.326,0.180,0.625), (sx*0.326,0.278,1.045),
           0.014, square=True, bevel=0.005, material=walnut, body=seat)

# Sculpted wooden armrests and their tapered support posts; mirrored left/right.
for sx in (-1, 1):
    x = sx * 0.345
    # Thick vertical arm posts seat into the side aprons and meet the arm caps.
    for idx, y in enumerate((-0.300, 0.040)):
        bottom = (sx*0.290, y, 0.525)
        top = (sx*0.335, y, 0.704)
        dx, dz = top[0]-bottom[0], top[2]-bottom[2]
        v4.cylinder(f"arm_support_{sx}_{idx}", 0.022, math.sqrt(dx*dx+dz*dz),
                    ((bottom[0]+top[0])/2, y, (bottom[2]+top[2])/2),
                    rot=(0,math.atan2(dx,dz),0), radius_top=0.014, segments=16,
                    material=walnut, body=seat)
    v4.box(f"armrest_{sx}", (0.084, 0.440, 0.045), (x, -0.060, 0.724), bevel=0.020, material=walnut, body=seat)
    # Soft inset arm caps give the hand rests a comfortable upholstered surface.
    v4.box(f"arm_pad_{sx}", (0.064,0.390,0.018), (x,-0.060,0.7555), bevel=0.009,
           material=upholstery, body=seat)
    # End-grain cap details inset at the armrest front and rear.
    for sy in (-1, 1):
        v4.box(f"armrest_end_cap_{sx}_{sy}", (0.050, 0.004, 0.026), (x, -0.060+sy*0.218, 0.724),
               bevel=0.008, material=walnut_edge, body=seat)

# Bracket ears under seat frame, aligned to the upper pivot pins.
for sx in (-1, 1):
    x = sx * BASE_X
    for tag, y in (("front", Y_SF), ("rear", Y_SR)):
        v4.box(f"seat_{tag}_bracket_{sx}", (0.050, 0.065, 0.064), (x, y, 0.478), bevel=0.008, material=steel, body=seat)
        v4.box(f"seat_{tag}_gusset_{sx}", (0.050, 0.090, 0.014), (x, y, 0.507), bevel=0.004, material=steel, body=seat)

# Move the entire seat/back/arm rigid assembly down so its hanging pivots sit below the base posts.
# Its seat-end brackets were authored at z=.445 before this offset, so they now meet z=.300.
seat.location.z = -SEAT_DROP

# Stainless pivot caps sit directly on the reinforced link eyes and move with their link.
for tag, y, z, owner in (("front_lower",Y_FRONT,Z_BASE_PIVOT,front_links), ("rear_lower",Y_REAR,Z_BASE_PIVOT,rear_links),
                         ("front_upper",Y_SF,Z_SEAT_PIVOT,front_links), ("rear_upper",Y_SR,Z_SEAT_PIVOT,rear_links)):
    if "lower" in tag:
        continue  # Lower pivots use the new frame-mounted bushings and outer flanges.
    for sx in (-1, 1):
        x = sx * LINK_X
        v4.cylinder(f"{tag}_pivot_cap_{sx}", 0.012, 0.008, (x+sx*0.018, y, z), rot=(0,math.pi/2,0),
                    material=chrome, body=owner)

# Four-bar: one tree and one loop closure. Each revolute axis spans the chair width (X).
# The links hang down from high base pivots to brackets below the seat rails.
v4.joint("base_front_pivot", "revolute", base, front_links,
         origin=(0,Y_FRONT,Z_BASE_PIVOT), axis=(1,0,0), limits=(-math.radians(12), math.radians(12)))
v4.joint("front_seat_pivot", "revolute", front_links, seat,
         origin=(0,Y_SF,Z_SEAT_PIVOT), axis=(1,0,0), limits=(-math.radians(12), math.radians(12)))
v4.joint("base_rear_pivot", "revolute", base, rear_links,
         origin=(0,Y_REAR,Z_BASE_PIVOT), axis=(1,0,0), limits=(-math.radians(12), math.radians(12)))
v4.joint("rear_seat_pivot", "revolute", rear_links, seat,
         origin=(0,Y_SR,Z_SEAT_PIVOT), axis=(1,0,0), limits=(-math.radians(12), math.radians(12)))

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