import cadquery as cq
import cadkit as ck

# Parameters
PLATE_L = 80.0        # Length of the cover
PLATE_W = 60.0        # Width of the cover
PLATE_T = 3.0         # Thickness of the main plate
RIM_H = 4.0           # Height of the bottom rim
RIM_T = 2.0           # Thickness of the rim wall
RIM_OFFSET = 2.0      # Offset of the rim from the plate edge
HOLE_D = 3.2          # Diameter of the mounting holes
HOLE_MARGIN = 6.0     # Distance of holes from the edges

# 1. Create the main plate
# Centered on XY plane, bottom at z=0
cover = (
    cq.Workplane("XY")
    .box(PLATE_L, PLATE_W, PLATE_T, centered=(True, True, False))
    .edges("|Z").fillet(2.0)
)

# 2. Create the rim (bottom lip)
# The rim is a hollow rectangle extruded downwards from the bottom face
rim_outer_l = PLATE_L - 2 * RIM_OFFSET
rim_outer_w = PLATE_W - 2 * RIM_OFFSET

# We create the rim by extruding a rectangle and then cutting a smaller rectangle from it
# Since the plate is at z=0 to z=PLATE_T, the rim goes from z=0 to z=-RIM_H
rim = (
    cq.Workplane("XY")
    .workplane(offset=0)
    .rect(rim_outer_l, rim_outer_w, centered=(True, True))
    .extrude(-RIM_H)
    .faces("<Z").workplane()
    .rect(rim_outer_l - 2 * RIM_T, rim_outer_w - 2 * RIM_T, centered=(True, True))
    .cutBlind(RIM_H)
)

# 3. Create mounting holes
# Calculate hole positions based on margin from edges
hx = (PLATE_L / 2) - HOLE_MARGIN
hy = (PLATE_W / 2) - HOLE_MARGIN
hole_points = [
    (hx, hy), (-hx, hy), (hx, -hy), (-hx, -hy)
]

# Apply holes to the combined geometry
final_model = (
    cover.union(rim)
    .faces(">Z").workplane()
    .pushPoints(hole_points)
    .hole(HOLE_D)
)

# Final touch: chamfer the bottom edges of the rim for easier assembly
final_model = final_model.edges("<Z").chamfer(0.5)

# Assembly for result
assy = cq.Assembly()
assy.add(final_model, name="cover_plate", color=cq.Color(0.8, 0.8, 0.8))

result = assy
