import cadquery as cq
import cadkit as ck

# Parameters
# Shaft dimensions
L1, D1 = 40.0, 20.0  # Left section
L2, D2 = 80.0, 25.0  # Middle section
L3, D3 = 40.0, 20.0  # Right section
TOTAL_L = L1 + L2 + L3 # 160mm

# Keyway dimensions
KEY_W = 6.0
KEY_L = 50.0
KEY_D = 3.0 # Standard depth for 25mm shaft

# Chamfer
CHAMFER = 1.0

# Constructing the shaft using cadkit
# ck.shaft builds from z=0 upwards. 
# Base segment is d, length. steps=[(d2, l2), ...] stack on top.
shaft_geom = ck.shaft(
    d=D1, 
    length=L1, 
    chamfer=CHAMFER, 
    steps=[(D2, L2), (D3, L3)]
)

# The keyway is located on the middle section (D2, L2)
# Middle section Z range: [L1, L1 + L2]
# Center of middle section: L1 + L2/2
key_z_center = L1 + L2 / 2
key_start = key_z_center - KEY_L / 2

# Create the keyway cutter as a separate solid
# We create a box and position it to cut into the shaft
key_cutter = (
    cq.Workplane("XY")
    .workplane(offset=key_start)
    .rect(KEY_W, KEY_D)
    .extrude(KEY_L)
    .translate((0, D2/2 - KEY_D/2, 0)) # Move to the top of the shaft
)

# Cut the keyway from the shaft
final_shaft = shaft_geom.cut(key_cutter)

# Ensure end faces have chamfers
final_shaft = final_shaft.edges(">Z").chamfer(CHAMFER)
final_shaft = final_shaft.edges("<Z").chamfer(CHAMFER)

# Assembly
assy = cq.Assembly()

# Correct way to rotate in CadQuery Assembly: 
# Use cq.Location(vector, rotation_vector, angle) or cq.Location().rotated(...)
# To lay the shaft along X axis, we rotate 90 deg around Y axis.
loc = cq.Location(cq.Vector(0, 0, 0), cq.Vector(0, 1, 0), 90)

assy.add(
    final_shaft, 
    name="stepped_shaft", 
    color=cq.Color(0.7, 0.7, 0.75), 
    loc=loc
)

result = assy
