"""A flawed answer, written by hand for the SiliconWit lesson on checking CAD code.
It looks right and runs, but it holds one mistake on purpose. Find it with:
    pytest -q --model flawed/answer_1.py
"""
"""NEMA 17 motor bracket, CadQuery 2.7. Sizes in mm, mass in g.

An L-bracket: the upright holds the motor on its front face (y < 0), the base
is screwed to a table or a 20 mm extrusion with two M5 screws, and two gussets
stiffen the corner behind the upright. The motor axis runs along Y.
"""
import math
import cadquery as cq

P = dict(
    width=50.0,         # X, across the bracket
    depth=40.0,         # Y, the base from the front face back
    height=50.0,        # Z, the upright from the table up
    t=5.0,              # thickness of the base and the upright
    axis_z=28.0,        # motor axis above the table
    pattern=31.0,       # NEMA 17 screw pattern, a square
    m3_hole=3.4,        # M3 clearance, ISO 273 medium
    pilot_hole=23.0,    # for the motor's 22 mm pilot
    m5_hole=5.5,        # M5 clearance, ISO 273 medium
    m5_x=12.5,          # base holes at x = +/- this
    m5_y=25.0,          # and this far back from the front face
    gusset=30.0,        # gusset legs, along the base and up the upright
    gusset_t=5.0,       # gusset thickness, flush with the sides
    density=2.70e-3,    # aluminium EN AW-6061, g per mm3 (2.70 g/cm3)
)


def motor_holes(p=P):
    """The four M3 screw centres in the upright, as (x, z)."""
    h = p["pattern"] / 2
    return [(sx * h, p["axis_z"] + sz * h) for sx in (-1, 1) for sz in (-1, 1)]


def make_bracket(p=P):
    w, d, H, t = p["width"], p["depth"], p["height"], p["t"]
    base = cq.Workplane("XY").box(w, d, t, centered=(True, False, False))
    upright = cq.Workplane("XY").box(w, t, H, centered=(True, False, False))
    body = base.union(upright)

    # two gussets: right triangles in the YZ plane, behind the upright, on the base
    g, gt = p["gusset"], p["gusset_t"]
    tri = [(t, t), (t + g, t), (t, t + g)]
    for x0 in (-w / 2, w / 2 - gt):
        gusset = cq.Workplane("YZ", origin=(x0, 0, 0)).polyline(tri).close().extrude(gt)
        body = body.union(gusset)

    # holes are cut where the requirement puts them, in bracket coordinates
    def through_y(x, z, dia):   # a hole through the upright, along Y
        return cq.Workplane("XZ", origin=(x, t + 1, z)).circle(dia / 2).extrude(t + 2)

    def through_z(x, y, dia):   # a hole through the base, along Z
        return cq.Workplane("XY", origin=(x, y, -1)).circle(dia / 2).extrude(t + 2)

    # the motor holes, centred on the front face of the upright
    front = body.faces("<Y").workplane(centerOption="CenterOfBoundBox")
    body = front.hole(p["pilot_hole"])
    front = body.faces("<Y").workplane(centerOption="CenterOfBoundBox")
    body = front.rect(p["pattern"], p["pattern"], forConstruction=True).vertices().hole(p["m3_hole"])
    for x in (-p["m5_x"], p["m5_x"]):
        body = body.cut(through_z(x, p["m5_y"], p["m5_hole"]))
    return body


def mass_g(part, p=P):
    """Mass in grams: volume in mm3 times density in g/mm3."""
    return part.val().Volume() * p["density"]


if __name__ == "__main__":
    b = make_bracket()
    bb = b.val().BoundingBox()
    print(f"volume {b.val().Volume():.1f} mm3, mass {mass_g(b):.1f} g")
    print(f"size {bb.xlen:.1f} x {bb.ylen:.1f} x {bb.zlen:.1f} mm")
    cq.exporters.export(b, "motor_bracket.step")
    print("wrote motor_bracket.step")
