"""Detailed wall-mounted can crusher. Run with Blender's background Python."""
import math
import os
import sys
import bpy

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

from mathutils import Vector

v4.reset()

# Finishes
red = v4.painted("crusher_red_powdercoat", (0.72, 0.055, 0.035), roughness=0.3, coat=0.45)
dark_red = v4.painted("formed_red_steel", (0.48, 0.035, 0.025), roughness=0.36, coat=0.25)
steel = v4.metal("brushed_stainless", (0.72, 0.74, 0.76), roughness=0.29)
zinc = v4.metal("zinc_plated_hardware", (0.58, 0.61, 0.63), roughness=0.34, brushed=False)
black = v4.rubber("charcoal_grip", (0.045, 0.05, 0.055), roughness=0.76)
pad_rubber = v4.rubber("press_pad_rubber", (0.075, 0.08, 0.085), roughness=0.88)
label_black = v4.mat("label_black", (0.025, 0.03, 0.035), roughness=0.58)
white = v4.mat("label_ink", (0.94, 0.91, 0.82), roughness=0.6)
yellow = v4.painted("safety_yellow", (0.98, 0.68, 0.08), roughness=0.42, coat=0.2)

# Dimensions in metres. The user faces the negative-Y front.
W = 0.116
PIVOT = (0.0, -0.005, 0.315)
SHOE_PIN = (0.0, -0.180, 0.210)

frame = v4.body("frame")
lever = v4.body("lever")
shoe = v4.body("pressure_plate")

# Fixed wall plate and folded frame rails.
wall_plate = v4.box("wall_mount_plate", (W, 0.012, 0.350), (0, 0.055, 0.185), bevel=0.003,
                    material=red, body=frame)
# Four rounded vertical key slots are cut through the backplate; the screw heads sit in them.
for sx in (-1, 1):
    for z in (0.055, 0.315):
        cutter = v4.box(f"mount_slot_cutter_{sx}_{z}", (0.014, 0.026, 0.022),
                        (sx * 0.043, 0.055, z), bevel=0.006)
        v4.boolean(wall_plate, cutter)
for sx in (-1, 1):
    x = sx * 0.051
    v4.box(f"backplate_edge_fold_{sx}", (0.010, 0.012, 0.305), (x, 0.040, 0.190), bevel=0.002,
           material=dark_red, body=frame)
    # Pivot cheek plates are set outside the moving crank cheeks.
    v4.box(f"pivot_cheek_{sx}", (0.010, 0.090, 0.080), (sx * 0.045, 0.002, 0.315), bevel=0.003,
           material=dark_red, body=frame)

# Broad lower anvil, extended under the resting shoe to make a real can-loading cup.
v4.box("anvil_deck", (0.108, 0.280, 0.018), (0, -0.085, 0.018), bevel=0.003,
       material=steel, body=frame)
v4.box("anvil_front_lip", (0.108, 0.012, 0.018), (0, -0.215, 0.036), bevel=0.002,
       material=zinc, body=frame)

# Broad triangular side webs welded between the wall plate and tray, instead of thin rods.
def add_gusset(name, x_inner, x_outer):
    yb, z0, yt, zt = 0.049, 0.027, -0.205, 0.145
    verts = [(x_inner, yb, z0), (x_inner, yb, zt), (x_inner, yt, z0),
             (x_outer, yb, z0), (x_outer, yb, zt), (x_outer, yt, z0)]
    faces = [(0, 1, 2), (3, 5, 4), (0, 3, 4, 1), (1, 4, 5, 2), (2, 5, 3, 0)]
    mesh = bpy.data.meshes.new(name + "_mesh")
    mesh.from_pydata(verts, [], faces)
    mesh.update()
    obj = bpy.data.objects.new(name, mesh)
    v4._finish(obj, frame, dark_red, bevel=0.0015, segments=3, smooth=False)

for sx in (-1, 1):
    x_inner, x_outer = ((0.052, 0.058) if sx > 0 else (-0.058, -0.052))
    add_gusset(f"anvil_gusset_plate_{sx}", x_inner, x_outer)
    # Low rails keep the can centred; they run the full cup length and meet the tray.
    v4.box(f"anvil_side_guide_{sx}", (0.008, 0.250, 0.018), (sx * 0.048, -0.085, 0.036), bevel=0.002,
           material=dark_red, body=frame)

# Wall fixings: four visible low-profile screw heads and slots on the backplate face.
for sx in (-1, 1):
    for z in (0.055, 0.315):
        x = sx * 0.043
        v4.cylinder(f"mount_screw_{sx}_{z}", 0.006, 0.0035, (x, 0.0475, z),
                    rot=(math.pi / 2, 0, 0), segments=32, bevel=0.0007, material=zinc, body=frame)
        v4.box(f"screw_slot_{sx}_{z}", (0.006, 0.0008, 0.0012), (x, 0.04565, z), bevel=0.0003,
               material=label_black, body=frame)

# Maker badge and operating label, both bonded onto the front face of the mount plate.
badge = v4.box("maker_badge", (0.084, 0.003, 0.034), (0, 0.0465, 0.170), bevel=0.002,
               material=label_black, body=frame)
v4.text("badge_name", "CAN\nCRUSHER", 0.010, loc=(0, 0.0447, 0.170), rot=(math.pi / 2, 0, 0),
        material=white, body=frame, on=badge, height=0.0006)
for sx in (-1, 1):
    for sz in (-1, 1):
        v4.cylinder(f"badge_rivet_{sx}_{sz}", 0.0023, 0.0018,
                    (sx * 0.035, 0.0438, 0.170 + sz * 0.012), rot=(math.pi / 2, 0, 0),
                    segments=20, bevel=0.0003, material=zinc, body=frame)
v4.box("warning_label", (0.084, 0.003, 0.034), (0, 0.0465, 0.214), bevel=0.0015,
       material=yellow, body=frame)
v4.text("warning_text", "KEEP HANDS CLEAR", 0.0064, loc=(0, 0.0447, 0.214), rot=(math.pi / 2, 0, 0),
        material=label_black, body=frame, on="auto", height=0.00035)

# Main lever: long raised handle and short downward/front crank cheeks are one rigid body.
# The two forged crank straps run from the pivot to the shoe hinge and straddle the shoe.
for sx in (-1, 1):
    v4.rod(f"crank_cheek_{sx}", (sx * 0.027, PIVOT[1], PIVOT[2]),
           (sx * 0.027, SHOE_PIN[1], SHOE_PIN[2]), 0.008, square=True,
           material=red, body=lever)
# Long handle stem has a slight forward/up sweep; it meets the pivot hub and grip sleeve.
handle_end = (0.0, -0.412, 0.468)
v4.rod("lever_handle_stem", PIVOT, handle_end, 0.011, square=True, material=red, body=lever)
v4.sphere("pivot_hub", 0.022, PIVOT, material=red, body=lever)

# A transverse pivot pin with stepped retaining washers, all carried by the lever.
v4.cylinder("main_pivot_pin", 0.008, 0.086, PIVOT, rot=(0, math.pi / 2, 0),
            material=zinc, body=lever)
for sx in (-1, 1):
    v4.cylinder(f"main_pivot_washer_{sx}", 0.014, 0.003, (sx * 0.037, PIVOT[1], PIVOT[2]),
                rot=(0, math.pi / 2, 0), material=steel, body=lever)
    v4.cylinder(f"main_pivot_cap_{sx}", 0.006, 0.003, (sx * 0.040, PIVOT[1], PIVOT[2]),
                rot=(0, math.pi / 2, 0), material=zinc, body=lever)

# Ergonomic ribbed sleeve over the outer end of the handle.
grip_start = Vector((0.0, -0.300, 0.423))
grip_end = Vector(handle_end)
gdir = (grip_end - grip_start).normalized()
grot = gdir.to_track_quat("Z", "Y").to_euler()
gl = (grip_end - grip_start).length
profile = [(0, 0), (0.016, 0), (0.018, 0.006)]
for i in range(1, 9):
    z = gl * i / 9
    profile.extend([(0.018, z - 0.0015), (0.020, z), (0.018, z + 0.0015)])
profile.extend([(0.018, gl - 0.006), (0.016, gl), (0, gl)])
v4.lathe("ribbed_grip", profile, loc=grip_start, rot=grot, material=black, body=lever)
v4.lathe("grip_end_cap", [(0, 0), (0.015, 0), (0.017, 0.003), (0.015, 0.006), (0, 0.006)],
         loc=grip_end - gdir * 0.001, rot=grot, material=red, body=lever)

# Distal hinge pin, straddled by the crank cheeks and joined to the pressure shoe.
v4.cylinder("shoe_hinge_pin", 0.006, 0.078, SHOE_PIN, rot=(0, math.pi / 2, 0),
            material=zinc, body=shoe)
for sx in (-1, 1):
    v4.cylinder(f"shoe_hinge_washer_{sx}", 0.011, 0.003, (sx * 0.041, SHOE_PIN[1], SHOE_PIN[2]),
                rot=(0, math.pi / 2, 0), material=steel, body=shoe)
    v4.cylinder(f"shoe_hinge_cap_{sx}", 0.0045, 0.003, (sx * 0.044, SHOE_PIN[1], SHOE_PIN[2]),
                rot=(0, math.pi / 2, 0), material=zinc, body=shoe)

# Bright annular bushings on the outer faces of the lever cheeks make the pin-through-clevis clear.
for sx in (-1, 1):
    v4.torus(f"shoe_hinge_bushing_{sx}", 0.008, 0.0017,
             loc=(sx * 0.035, SHOE_PIN[1], SHOE_PIN[2]), rot=(0, math.pi / 2, 0),
             material=steel, body=lever)

# Wide press shoe: formed steel pad with shallow returns and a raised stiffening rib.
v4.box("pressing_shoe", (0.088, 0.092, 0.014), (0, SHOE_PIN[1], SHOE_PIN[2] - 0.010), bevel=0.003,
       material=steel, body=shoe)
for sx in (-1, 1):
    v4.box(f"shoe_return_{sx}", (0.004, 0.078, 0.012), (sx * 0.042, SHOE_PIN[1], SHOE_PIN[2] - 0.001),
           bevel=0.0015, material=zinc, body=shoe)
v4.box("shoe_stiffener_rib", (0.048, 0.010, 0.004), (0, SHOE_PIN[1], SHOE_PIN[2] + 0.001), bevel=0.0015,
       material=zinc, body=shoe)
# Replaceable rubber face pad bonded flush to the pressing face.
v4.box("shoe_rubber_face", (0.072, 0.074, 0.008), (0, SHOE_PIN[1], SHOE_PIN[2] - 0.021), bevel=0.003,
       material=pad_rubber, body=shoe)

# Articulation: positive lever rotation lowers the crank and press shoe toward the anvil.
v4.joint("lever_pivot", "revolute", frame, lever, origin=PIVOT, axis=(1, 0, 0),
         limits=(0.0, 1.0))
v4.joint("shoe_hinge", "revolute", lever, shoe, origin=SHOE_PIN, axis=(1, 0, 0),
         limits=(-0.30, 0.30))

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