"""Original Zen SKADIS-compatible tool cup. Units: mm. Requires cadquery 2.8.

Run: python skadis-holder.py --output ./skadis-models
Edit the dimensions below, rerun, and import the STEP in Zen.
X = across board, Y = forward from board, Z = up. No printer commands.
Nominal interface: 5 x 15 rounded slots, 40 mm pitch, 5 mm board.
Design reference: Springcraft's SKADIS Generator technical specifications:
https://marketplace.autodesk.com/apps/880f2e71-a0b1-41ec-b148-294452d2419c
This original design has not been physically test-printed or load-rated.
"""
from pathlib import Path
import argparse
import json
import cadquery as cq

WIDTH = 96.0
DEPTH = 46.0
HEIGHT = 64.0
CUP_HEIGHT = 48.0
WALL = 3.2
CORNER_RADIUS = 5.0
DIVIDER_X = 8.0
HOOK_PITCH = 40.0
HOOK_WIDTH = 4.2
BOARD_GAP = 5.6  # rear face of holder to inside of retaining lip
LIP_DEPTH = 3.0
SLOT_WIDTH = 5.0
SLOT_HEIGHT = 15.0
BOARD_THICKNESS = 5.0
UPPER_SLOT_Z = 52.0
INSERT_LIFT = 4.75


def box(w, d, h, x, y, z):
    return cq.Workplane("XY").box(w, d, h).translate((x, y, z))


def rounded_box(w, d, h, x, y, z, r):
    return cq.Workplane("XY").box(w, d, h).edges("|Z").fillet(r).translate((x, y, z))


def anchor(x):
    # Both hooks push through the slots while lifted, then drop behind the board.
    # Rounded XZ cross-sections leave clearance at the capsule-shaped slot ends.
    neck = cq.Workplane("XY").box(HOOK_WIDTH, BOARD_GAP + 1.8, 4).edges("|Y").fillet(.7)
    neck = neck.translate((x, (1 - BOARD_GAP - .8) / 2, UPPER_SLOT_Z - 3.5))
    lip = cq.Workplane("XY").box(HOOK_WIDTH, LIP_DEPTH, 8.5).edges("|Y").fillet(.7)
    lip = lip.translate((x, -BOARD_GAP - LIP_DEPTH / 2, UPPER_SLOT_Z - 5.75))
    guide = cq.Workplane("XY").box(HOOK_WIDTH, 5.8, 4).edges("|Y").fillet(.7)
    guide = guide.translate((x, -1.9, UPPER_SLOT_Z - HOOK_PITCH - 3.5))
    return neck.union(lip).union(guide)


def make_holder():
    if not (WIDTH >= 64 and DEPTH >= 24 and HEIGHT >= 62 and WALL >= 2.4):
        raise ValueError("Keep enough body around the 40 mm mounting pattern.")
    outer = rounded_box(WIDTH, DEPTH, CUP_HEIGHT, 0, DEPTH / 2, CUP_HEIGHT / 2, CORNER_RADIUS)
    cavity = rounded_box(WIDTH - WALL * 2, DEPTH - WALL * 2, CUP_HEIGHT,
                         0, DEPTH / 2, CUP_HEIGHT / 2 + WALL, CORNER_RADIUS - WALL)
    body = outer.cut(cavity)
    # Back rises above the cup; overlap the shell rather than touching faces only.
    back = box(WIDTH - 2 * CORNER_RADIUS, WALL, HEIGHT, 0, WALL / 2, HEIGHT / 2)
    divider = box(WALL, DEPTH - WALL, CUP_HEIGHT - WALL, DIVIDER_X,
                  DEPTH / 2, (CUP_HEIGHT + WALL) / 2)
    body = body.union(back).union(divider)
    for x in (-HOOK_PITCH / 2, HOOK_PITCH / 2):
        body = body.union(anchor(x))
    return body.clean()


def make_coupon():
    return box(12, WALL, HEIGHT, 0, WALL / 2, HEIGHT / 2).union(anchor(0)).clean()


def make_board(width=180, height=160):
    # Reference board only. Not included in the holder downloads/import.
    board = box(width, BOARD_THICKNESS, height, 0, -BOARD_THICKNESS / 2 - .3, 42)
    for row in range(-3, 5):
        z = UPPER_SLOT_Z + row * 20
        for col in range(-3, 4):
            x = col * 40 + (20 if row % 2 == 0 else 0)
            slot = cq.Workplane("XZ").center(x, z).slot2D(SLOT_HEIGHT, SLOT_WIDTH, 90).extrude(20, both=True)
            board = board.cut(slot)
    return board.clean()


def export(output):
    output.mkdir(parents=True, exist_ok=True)
    info = {}
    for name, model in (("skadis-tool-holder", make_holder()), ("skadis-fit-test", make_coupon())):
        shape = model.val()
        assert shape.isValid() and len(model.solids().vals()) == 1
        cq.exporters.export(model, str(output / (name + ".step")))
        cq.exporters.export(model, str(output / (name + ".stl")), tolerance=.06, angularTolerance=.12)
        bb = shape.BoundingBox()
        info[name] = {"sizeMm": [round(bb.xlen, 3), round(bb.ylen, 3), round(bb.zlen, 3)],
                      "volumeMm3": round(shape.Volume(), 2), "validSolid": True}
    cq.exporters.export(make_board(), str(output / "skadis-reference-board.stl"), tolerance=.08, angularTolerance=.16)
    (output / "dimensions.json").write_text(json.dumps(info, indent=2) + "\n")
    print(json.dumps(info))


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--output", type=Path, default=Path("skadis-models"))
    export(parser.parse_args().output)
