"""Checks for the NEMA 17 motor bracket, written from the requirement, before any model.

Every number here comes from the requirement table, never from the model's code:
a test that reads its numbers from the code under test agrees with any mistake.
Run:  pytest -q                         (tests bracket.py)
      pytest -q --model other_file.py   (tests another answer)
"""
import math
import cadquery as cq
import pytest

# the requirement, mm
WIDTH, DEPTH, HEIGHT = 50.0, 40.0, 50.0
T = 5.0                    # base and upright thickness
MIN_WALL = 4.0             # no plate thinner than this
MIN_WEB = 3.0              # metal left around every hole, at least
AXIS_Z = 28.0              # motor axis above the table
HALF = 31.0 / 2            # NEMA 17 screw pattern, 31 mm square
M3, PILOT, M5 = 3.4, 23.0, 5.5          # clearance holes
M5_AT = [(-12.5, 25.0), (12.5, 25.0)]   # base holes (x, y)
GUSSET, GUSSET_T = 30.0, 5.0            # two gussets: legs, thickness
DENSITY = 2.70e-3          # aluminium 6061, g/mm3
TOL = 0.01                 # mm, for sizes and places

MOTOR_HOLES = [(sx * HALF, AXIS_Z + sz * HALF) for sx in (-1, 1) for sz in (-1, 1)]


def hand_volume():
    """The volume worked out by hand: plates and gussets, minus the holes."""
    base = WIDTH * DEPTH * T
    upright = WIDTH * T * (HEIGHT - T)
    gussets = 2 * 0.5 * GUSSET * GUSSET * GUSSET_T
    holes = math.pi * T * ((PILOT / 2) ** 2 + 4 * (M3 / 2) ** 2 + 2 * (M5 / 2) ** 2)
    return base + upright + gussets - holes


def circles(part):
    """Every circular edge: (centre, diameter)."""
    return [(e.Center(), 2 * e.radius()) for e in part.edges("%CIRCLE").vals()]


def hole_at(part, x, y, z):
    """The diameter of the hole whose edge is centred at (x, y, z), or None."""
    for c, dia in circles(part):
        if (c - cq.Vector(x, y, z)).Length < TOL:
            return dia
    return None


def thickness_at(part, x, y, z, axis):
    """Metal along a thin probe through (x, y, z), parallel to axis 'x', 'y' or 'z'."""
    size = {"x": (200, 0.2, 0.2), "y": (0.2, 200, 0.2), "z": (0.2, 0.2, 200)}[axis]
    probe = cq.Workplane("XY").box(*size).translate((x, y, z))
    for piece in part.intersect(probe).solids().vals():     # the run of metal through the point
        bb = piece.BoundingBox()
        if bb.xmin <= x <= bb.xmax and bb.ymin <= y <= bb.ymax and bb.zmin <= z <= bb.zmax:
            return {"x": bb.xlen, "y": bb.ylen, "z": bb.zlen}[axis]
    return 0.0


def overlap(part, other):
    """Volume shared by the part and another solid, mm3."""
    common = part.intersect(other).vals()
    return sum(s.Volume() for s in common)


# 1. it is one valid solid ---------------------------------------------------
def test_one_valid_solid(part):
    solids = part.solids().vals()
    assert len(solids) == 1, f"{len(solids)} solids, expected 1"
    assert solids[0].isValid()


# 2. outside size ---------------------------------------------------------
def test_size(part):
    bb = part.val().BoundingBox()
    got = (round(bb.xlen, 2), round(bb.ylen, 2), round(bb.zlen, 2))
    assert got == (WIDTH, DEPTH, HEIGHT), f"size {got}"
    assert abs(bb.zmin) < TOL and abs(bb.ymin) < TOL, "base on z = 0, front face on y = 0"


# 3. volume, against the hand calculation ----------------------------------
def test_volume(part):
    v, expect = part.val().Volume(), hand_volume()
    assert v == pytest.approx(expect, rel=1e-3), f"{v:.1f} mm3, expected {expect:.1f}"


# 4. mass from density -------------------------------------------------------
def test_mass(model, part):
    expect = hand_volume() * DENSITY          # 62.8 g
    got = model.mass_g(part)
    assert got == pytest.approx(expect, rel=0.01), f"{got:.1f} g, expected {expect:.1f} g"


# 5. holes where the motor needs them ---------------------------------------
def test_hole_positions(part):
    wanted = [(0, AXIS_Z)] + MOTOR_HOLES
    missing = [(x, z) for x, z in wanted if hole_at(part, x, 0, z) is None]
    found = sorted({round(c.z, 2) for c, _ in circles(part) if abs(c.y) < TOL})
    assert not missing, f"{len(missing)} of 5 holes not in place: holes at z = {found}, wanted z = 12.5, 28, 43.5"
    for x, y in M5_AT:
        assert hole_at(part, x, y, 0) is not None, f"no M5 hole at x={x:g} y={y:g}"


# 6. hole diameters --------------------------------------------------------
def test_hole_diameters(part):
    want = [("pilot", 0, 0, AXIS_Z, PILOT)]
    want += [("M3", x, 0, z, M3) for x, z in MOTOR_HOLES]
    want += [("M5", x, y, 0, M5) for x, y in M5_AT]
    wrong = []
    for name, x, y, z, dia in want:
        got = hole_at(part, x, y, z)          # a hole not in place is test 5's job
        if got is not None and abs(got - dia) > TOL:
            wrong.append(f"{name} {got:g} mm, not {dia:g}")
    assert not wrong, "; ".join(sorted(set(wrong)))
    n = len(circles(part))
    assert n == 2 * 7, f"{n} round edges: 7 holes make 14, so something else is cut"


# 7. wall thickness ----------------------------------------------------------
@pytest.mark.parametrize("x, y, z, axis", [
    pytest.param(0, 2.5, 45, "y", id="upright top"),
    pytest.param(-17.5, 2.5, 8, "y", id="upright low"),
    pytest.param(22, 38, 2.5, "z", id="base back"),
    pytest.param(0, 20, 2.5, "z", id="base middle"),
    pytest.param(22.5, 15, 10, "x", id="gusset"),
])
def test_wall_thickness(part, x, y, z, axis):
    got = thickness_at(part, x, y, z, axis)
    assert got >= MIN_WALL, f"{got:.2f} mm of metal, at least {MIN_WALL:g} needed"


# 8. metal left around every hole ---------------------------------------------
def test_metal_around_holes(part):
    for name, face in [("front face", part.faces("<Y").val()), ("base underside", part.faces("<Z").val())]:
        holes, edge = face.innerWires(), face.outerWire()
        webs = [h.distance(edge) for h in holes]
        webs += [a.distance(b) for i, a in enumerate(holes) for b in holes[i + 1:]]
        assert min(webs) >= MIN_WEB, f"{name}: only {min(webs):.2f} mm of metal at a hole"


# 9. the motor and its screws fit ------------------------------------------
def test_motor_fits(part):
    # motor body, 42.3 mm square and 40 mm long, on the front face
    body = cq.Workplane("XZ").center(0, AXIS_Z).rect(42.3, 42.3).extrude(40)
    # its 22 mm pilot, 2 mm long, goes into the pilot hole
    pilot = cq.Workplane("XZ").center(0, AXIS_Z).circle(11.0).extrude(-2)
    assert overlap(part, body) < 1e-6, "the motor body runs into the bracket"
    assert body.val().BoundingBox().zmin >= 1.0, "the motor touches the table"
    assert part.val().distance(pilot.val()) >= 0.2, "the pilot has no clearance in its hole"
    for x, z in MOTOR_HOLES:
        shank = cq.Workplane("XZ", origin=(x, 0, z)).circle(1.5).extrude(-T)
        head = cq.Workplane("XZ", origin=(x, T, z)).circle(5.5 / 2).extrude(-3)   # M3 cap head
        assert part.val().distance(shank.val()) >= 0.1, f"M3 screw at x={x:g} z={z:g} binds in its hole"
        assert overlap(part, head) < 1e-6, f"M3 head at x={x:g} z={z:g} hits the bracket"


# 10. the STEP file is a good one ----------------------------------------------
def test_step_export(part, tmp_path):
    f = tmp_path / "bracket.step"
    cq.exporters.export(part, str(f))
    assert f.read_text()[:13] == "ISO-10303-21;", "not a STEP file"
    back = cq.importers.importStep(str(f))
    solids = back.solids().vals()
    assert len(solids) == 1 and solids[0].isValid(), f"STEP holds {len(solids)} solids"
    v = solids[0].Volume()
    assert v == pytest.approx(hand_volume(), rel=1e-3), f"STEP volume {v:.1f} mm3, expected {hand_volume():.1f}"
    bb = solids[0].BoundingBox()
    assert (round(bb.xlen, 2), round(bb.ylen, 2), round(bb.zlen, 2)) == (WIDTH, DEPTH, HEIGHT)
