import cadquery as cq
import cadkit as ck

# Parameters
OD = 30.0            # Outer diameter of the sleeve (mm)
ID = 20.0            # Inner diameter (bore) (mm)
TOTAL_L = 40.0       # Total length of the sleeve (mm)
FLANGE_D = 40.0      # Diameter of the flange (mm)
FLANGE_T = 5.0      # Thickness of the flange (mm)
CHAMFER = 0.5        # Edge chamfer (mm)

# The sleeve body is the main cylinder
# We start from z=0. The flange is at the bottom.
# Sleeve height without flange = TOTAL_L - FLANGE_T
sleeve_h = TOTAL_L - FLANGE_T

# Create the flange (bottom part)
flange = (
    cq.Workplane("XY")
    .circle(FLANGE_D / 2)
    .extrude(FLANGE_T)
)

# Create the sleeve body (top part)
body = (
    cq.Workplane("XY")
    .workplane(offset=FLANGE_T)
    .circle(OD / 2)
    .extrude(sleeve_h)
)

# Combine flange and body
part = flange.union(body)

# Cut the inner bore through the whole part
part = part.cut(
    cq.Workplane("XY")
    .circle(ID / 2)
    .extrude(TOTAL_L)
)

# Apply chamfers to the edges
# 1. Bottom outer edge of the flange
# 2. Top outer edge of the sleeve
# 3. Top inner edge of the bore
# 4. Bottom inner edge of the bore
part = (
    part.edges(">Z").chamfer(CHAMFER) # Top outer and inner
       .edges("<Z").chamfer(CHAMFER) # Bottom outer and inner
)

# Final Assembly
assy = cq.Assembly()
assy.add(part, name="flanged_bushing", color=cq.Color(0.7, 0.7, 0.75))

result = assy
