#!/usr/bin/env python3
"""Check the welding table package from ruthensystems.com yourself.

Run it in the folder that holds the cut DXFs and manifest.json (or give the folder as the argument):

    pip install ezdxf
    python verify-welding-table.py

It reads the cut files with ezdxf (an independent, open-source DXF library) and works every expected
number out here, from the inputs in manifest.json only, with the rules below. The derived numbers in
manifest.json are never trusted: each is compared with the one found here.

  * hole grid: "s16" = 16 mm holes on a 50 mm grid, "s28" = 28 mm on 100 mm, "none" = no holes.
    Along a side of length len: n = floor((len - p) / p) + 1 holes, the first at (len - (n - 1) p) / 2,
    so the grid is centred and at least half a pitch from each edge;
  * ribs (flat bar on edge, thickness t, depth h): without a grid, the outer rib centre lines sit
    overhang + t/2 in from each edge and the rest equally spaced, n = ceil(span / spacing) spaces;
    with a grid a rib may only sit midway between two rows of holes or half a pitch outside the last
    row, at least 1/2 + t/2 from the edge; the outer ribs take the allowed place nearest to
    overhang + t/2 (the far one mirrored), the inner ones the allowed places nearest to an equal
    division into ceil(span / spacing) spaces, each place used once;
  * egg-crate: each rib runs to the outside faces of the outer ribs it crosses (cross ribs:
    span of the long ribs + t; long ribs: span of the cross ribs + t); slots t + 1/32 wide, h / 2 + 1/32
    deep, centred on each crossing; cross ribs slotted from the top, long ribs from the bottom;
  * laser-cut ribs: on each rib's top edge a tab 1.5 long midway between each two crossings, as high as
    the top plate is thick; a slot 1.5 + 2 x 0.015 long and t + 2 x 0.015 wide through the top over
    each tab; corners: top plate R1/2, cap and base plates R1/4, rib ends and tab tops R1/8, half-lap
    slot corners R1/32, a R1/16 relief circle centred on each tab root;
  * every hole edge at least 1/8 from every rib face and tab slot side;
  * legs: under the four outer rib crossings, plus at the inner cross rib nearest the middle on both
    long sides when the top is longer than 72; a corner leg's outside faces flush with the outer rib
    faces, its plates flush and running inward; a middle leg centred on its cross rib;
  * heights: plate underside = H - top plate; rib bottom = that - rib depth; levelling foot set at 1.5;
    1/4 cap and base plates; leg length = rib bottom - 1/4 - (1.5 + 1/4);
  * stretchers: square cut between leg faces on the leg centre lines, two per bay along the length,
    one at each pair of legs across;
  * shelf: out to the stretchers' outside faces, a notch round each leg (1/4 clear of the leg each side);
  * cut files: DXF R12 in inches, no audit errors; the top plate rectangle with one circle per hole at
    the grid points and a closed rectangle per tab slot; the two ribs (cross at y 0, long above it, 2
    clear of the cross rib's tabs): every line and arc of each outline where the slots, tabs, radii and
    reliefs put it; the two end plates side by side 2 apart with the 11/16 hole centred in the base
    plate; the shelf: every outline corner where the notches put it;
  * design rules: rib depth >= 6 x thickness and thickness <= top + 1/8; largest rib spacing <= 24;
    overhang 1 to 6 at the ends and the sides; holes 1/8 clear; two ribs each way and half laps >= 1;
    legs >= 12; stretchers between 2 above the base plates and 8 under the cap plates; the 5/8-11 heavy
    nut (1.0625 across flats) fits inside the leg with 1/32 a side; stretchers no bigger than the legs;
    a tab fits midway in the shortest bay with 1/2 clear each side;
  * weights: steel 0.2836 lb/in3 (within 0.5 %), the plates and ribs by their rounded outlines, square
    tube with A500 corners (outside radius 2 x wall, inside 1 x wall).

Exit status 0 and "ALL CHECKS PASSED" when everything holds.
"""
import json
import math
import sys
from pathlib import Path

import ezdxf

HERE = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(__file__).resolve().parent
TOL = 0.002
WTOL = 0.005
STEEL = 0.2836
SLOT_CLR, SLOT_EXTRA, NOTCH_CLR, PLATE_T, FOOT_H, FOOT_HOLE, NUT_AF = 1 / 32, 1 / 32, 1 / 4, 0.25, 1.5, 0.6875, 1.0625
TAB_L, TAB_CLR = 1.5, 0.015
R_TOP, R_PLATE, R_RIB, R_SLOT, R_RELIEF = 0.5, 0.25, 0.125, 1 / 32, 1 / 16
manifest = json.loads((HERE / "manifest.json").read_text())
I = manifest["inputs"]
L, W, H, TP = I["topLength"], I["topWidth"], I["heightToTop"], I["topPlate"]
GRID, OV, SPACING = I["holeGrid"], I["overhangWanted"], I["ribSpacingWanted"]
RT, RH = I["rib"]["thickness"], I["rib"]["depth"]
LEG, LEGW = I["legTube"]["size"], I["legTube"]["wall"]
RAIL, RAILW = I["stretcherTube"]["size"], I["stretcherTube"]["wall"]
SHELF_H, SHELF_T = I["stretcherTopAboveFloor"], I["shelfSheet"]

bad = 0


def check(text, ok, detail=""):
    global bad
    print(("OK    " if ok else "FAIL  ") + text + ("" if ok or not detail else f"  [{detail}]"))
    if not ok:
        bad += 1


def near(a, b, tol=TOL):
    return a is not None and b is not None and abs(a - b) <= tol


def near_w(a, b):
    return a is not None and abs(a - b) <= WTOL * max(abs(b), 1e-9)


def lists_near(a, b):
    return a is not None and len(a) == len(b) and all(near(x, y) for x, y in zip(a, b))


check("inputs inside the generator's ranges",
      36 <= L <= 96 and 24 <= W <= 48 and 30 <= H <= 42 and 1 <= OV <= 6 and 8 <= SPACING <= 24 and 4 <= SHELF_H <= 16,
      f"L {L} W {W} H {H} ov {OV} spacing {SPACING} stretchers {SHELF_H}")

# ---- grid
SPEC = {"s16": (16, 50), "s28": (28, 100)}.get(GRID)
D = P = None
if SPEC:
    D, P = SPEC[0] / 25.4, SPEC[1] / 25.4


def holes_along(length):
    if not SPEC:
        return []
    n = int(math.floor((length - P) / P + 1e-9)) + 1
    first = (length - (n - 1) * P) / 2
    return [first + i * P for i in range(n)]


HX, HY = holes_along(L), holes_along(W)
G = manifest["grid"]
if SPEC:
    check(f"grid {SPEC[0]} mm holes on {SPEC[1]} mm: {len(HX)} x {len(HY)} = {len(HX) * len(HY)}, centred",
          G is not None and G["holeMm"] == SPEC[0] and G["pitchMm"] == SPEC[1] and lists_near(G["alongLength"], HX)
          and lists_near(G["alongWidth"], HY) and G["count"] == len(HX) * len(HY),
          f"manifest {G and G['count']}")
    check("first holes at least half a pitch from the edges", HX[0] >= P / 2 - 1e-9 and HY[0] >= P / 2 - 1e-9)
else:
    check("plain top: no grid in the manifest", G is None)


# ---- ribs
def ribs_along(length, holes):
    want = OV + RT / 2
    if not SPEC:
        a, b = want, length - want
        n = max(1, math.ceil((b - a) / SPACING - 1e-9))
        return [a + (b - a) * i / n for i in range(n + 1)]
    allowed = [holes[0] + (k - 0.5) * P for k in range(len(holes) + 1)]
    allowed = [c for c in allowed if c - RT / 2 >= 0.5 - 1e-9]

    def nearest(v, pool):
        best = pool[0]
        for c in pool:
            if abs(c - v) < abs(best - v):
                best = c
        return best

    a = nearest(want, allowed)
    b = length - a
    inner = [c for c in allowed if a + 1e-9 < c < b - 1e-9]
    n = max(1, math.ceil((b - a) / SPACING - 1e-9))
    mid = []
    for j in range(1, n):
        pool = [c for c in inner if c not in mid]
        if pool:
            mid.append(nearest(a + (b - a) * j / n, pool))
    return [a] + sorted(mid) + [b]


XS, YS = ribs_along(L, HX), ribs_along(W, HY)
R = manifest["ribs"]
check(f"cross ribs at x = {', '.join(f'{v:.3f}' for v in XS)}", lists_near(R["crossAtX"], XS), f"manifest {R['crossAtX']}")
check(f"long ribs at y = {', '.join(f'{v:.3f}' for v in YS)}", lists_near(R["longAtY"], YS), f"manifest {R['longAtY']}")
gap_x = max(b - a for a, b in zip(XS, XS[1:]))
gap_y = max(b - a for a, b in zip(YS, YS[1:]))
over_x, over_y = XS[0] - RT / 2, YS[0] - RT / 2
check(f"largest spacing {gap_x:.4f} / {gap_y:.4f}, overhang {over_x:.4f} ends / {over_y:.4f} sides",
      near(R["largestSpacingX"], gap_x) and near(R["largestSpacingY"], gap_y) and near(R["overhangEnds"], over_x) and near(R["overhangSides"], over_y))
CROSS_LEN, LONG_LEN = YS[-1] - YS[0] + RT, XS[-1] - XS[0] + RT
CROSS_SLOTS = [y - YS[0] + RT / 2 for y in YS]
LONG_SLOTS = [x - XS[0] + RT / 2 for x in XS]
SW, SD = RT + SLOT_CLR, RH / 2 + SLOT_EXTRA
check(f"cross rib {len(XS)} off {CROSS_LEN:.4f} long, {len(CROSS_SLOTS)} slots from the top",
      R["cross"]["qty"] == len(XS) and near(R["cross"]["length"], CROSS_LEN) and R["cross"]["slotsFrom"] == "top" and lists_near(R["cross"]["slotCentres"], CROSS_SLOTS))
check(f"long rib {len(YS)} off {LONG_LEN:.4f} long, {len(LONG_SLOTS)} slots from the bottom",
      R["long"]["qty"] == len(YS) and near(R["long"]["length"], LONG_LEN) and R["long"]["slotsFrom"] == "bottom" and lists_near(R["long"]["slotCentres"], LONG_SLOTS))
check(f"slots {SW:.4f} wide x {SD:.4f} deep", near(R["slot"]["width"], SW) and near(R["slot"]["depth"], SD))
mids = lambda v: [(a + b) / 2 for a, b in zip(v, v[1:])]
CROSS_TABS = [y - YS[0] + RT / 2 for y in mids(YS)]
LONG_TABS = [x - XS[0] + RT / 2 for x in mids(XS)]
check(f"tabs: {len(CROSS_TABS)} on each cross rib, {len(LONG_TABS)} on each long rib, midway between crossings",
      lists_near(R["cross"]["tabCentres"], CROSS_TABS) and lists_near(R["long"]["tabCentres"], LONG_TABS))
SLOT_LEN, SLOT_WID = TAB_L + 2 * TAB_CLR, RT + 2 * TAB_CLR
TAB_SLOTS = [(x, y, "y") for x in XS for y in mids(YS)] + [(x, y, "x") for y in YS for x in mids(XS)]
TS = manifest["tabSlots"]
check(f"{len(TAB_SLOTS)} tab slots {SLOT_LEN:.3f} x {SLOT_WID:.3f} in the top",
      TS["count"] == len(TAB_SLOTS) and near(TS["length"], SLOT_LEN) and near(TS["width"], SLOT_WID)
      and len(TS["at"]) == len(TAB_SLOTS) and all(near(a[0], b[0]) and near(a[1], b[1]) and a[2] == b[2] for a, b in zip(TS["at"], TAB_SLOTS)))
hole_min = slot_min = 0.0
if SPEC:
    hole_min = min([abs(h - r) - RT / 2 - D / 2 for h in HX for r in XS] + [abs(h - r) - RT / 2 - D / 2 for h in HY for r in YS])
    slot_min = hole_min - TAB_CLR
    check(f"nearest hole edge {hole_min:.4f} from a rib face, {slot_min:.4f} from a tab slot", near(G["nearestToRibFace"], hole_min) and near(TS["nearestHole"], slot_min))

# ---- legs and heights
ribx = [XS[0], XS[-1]]
if L > 72 and len(XS) > 2:
    inner = XS[1:-1]
    ribx.insert(1, min(inner, key=lambda c: abs(c - L / 2)))
END = LEG + 1


def place(v, lo, hi):
    if abs(v - lo) < 1e-9:
        o = lo - RT / 2
        return o + LEG / 2, (o, o + END)
    if abs(v - hi) < 1e-9:
        o = hi + RT / 2
        return o - LEG / 2, (o - END, o)
    return v, (v - END / 2, v + END / 2)


legx = [place(x, XS[0], XS[-1])[0] for x in ribx]
legy = [place(y, YS[0], YS[-1])[0] for y in (YS[0], YS[-1])]
LEGS = [(place(x, XS[0], XS[-1])[0], place(y, YS[0], YS[-1])[0]) for x in ribx for y in (YS[0], YS[-1])]
LEG_PLATES = [place(x, XS[0], XS[-1])[1] + place(y, YS[0], YS[-1])[1] for x in ribx for y in (YS[0], YS[-1])]
check(f"{len(LEGS)} legs at the outer rib crossings, corner legs flush with the outer rib faces", manifest["legs"]["qty"] == len(LEGS)
      and all(near(a[0], b[0]) and near(a[1], b[1]) for a, b in zip(manifest["legs"]["at"], LEGS))
      and all(lists_near(a, list(b)) for a, b in zip(manifest["legs"]["plates"], LEG_PLATES)), f"manifest {manifest['legs']['at']}")
Z_PLATE, Z_RIB = H - TP, H - TP - RH
LEG_LEN = Z_RIB - PLATE_T - (FOOT_H + PLATE_T)
lv = manifest["levels"]
check(f"plate underside {Z_PLATE:.4f}, rib bottom {Z_RIB:.4f}, leg {LEG_LEN:.4f}",
      near(lv["plateUnderside"], Z_PLATE) and near(lv["ribBottom"], Z_RIB) and near(lv["basePlateUnderside"], FOOT_H) and near(manifest["legs"]["length"], LEG_LEN))
check(f"cap and base plates 1/4 x {END:.3f} square", near(manifest["fixed"]["endPlate"]["size"], END) and near(manifest["fixed"]["endPlate"]["thickness"], PLATE_T))

# ---- stretchers
bays = [b - a for a, b in zip(legx, legx[1:])]
want = {}
for b in bays:
    k = round(b, 4)
    want[k] = want.get(k, 0) + 2
long_st = sorted((round(k - LEG, 4), q) for k, q in want.items())
got_long = sorted((round(s["length"], 4), s["qty"]) for s in manifest["stretchers"] if s["along"] == "x")
got_cross = [(round(s["length"], 4), s["qty"]) for s in manifest["stretchers"] if s["along"] == "y"]
check("long stretchers " + ", ".join(f"{q} x {l:.4f}" for l, q in long_st),
      len(got_long) == len(long_st) and all(near(a[0], b[0]) and a[1] == b[1] for a, b in zip(got_long, long_st)), f"manifest {got_long}")
check(f"cross stretchers {len(legx)} x {legy[1] - legy[0] - LEG:.4f}", len(got_cross) == 1 and near(got_cross[0][0], legy[1] - legy[0] - LEG) and got_cross[0][1] == len(legx))

# ---- shelf
SH = manifest["shelf"]
shelf_area = 0.0
if SHELF_T > 0:
    sx0, sx1, sy0, sy1 = legx[0] - RAIL / 2, legx[-1] + RAIL / 2, legy[0] - RAIL / 2, legy[-1] + RAIL / 2
    hh = LEG / 2 + NOTCH_CLR
    notch = 0.0
    SHELF_CORNERS = {(sx0, sy0), (sx1, sy0), (sx1, sy1), (sx0, sy1)}
    for (x, y) in LEGS:
        a0, a1, b0, b1 = max(sx0, x - hh), min(sx1, x + hh), max(sy0, y - hh), min(sy1, y + hh)
        notch += (a1 - a0) * (b1 - b0)
        # a notch cut into the outline: its corners on the shelf edge replace the shelf corner it takes
        box = [(a0, b0), (a1, b0), (a1, b1), (a0, b1)]
        SHELF_CORNERS -= {c for c in list(SHELF_CORNERS) if a0 - 1e-9 <= c[0] <= a1 + 1e-9 and b0 - 1e-9 <= c[1] <= b1 + 1e-9}
        SHELF_CORNERS |= set(box)
    # a notch corner that lands on a shelf corner is not a turn of the outline
    SHELF_CORNERS -= {c for c in list(SHELF_CORNERS) if (near(c[0], sx0) or near(c[0], sx1)) and (near(c[1], sy0) or near(c[1], sy1))}
    SHELF_CORNERS = {(x - sx0, y - sy0) for x, y in SHELF_CORNERS}
    shelf_area = (sx1 - sx0) * (sy1 - sy0) - notch
    check(f"shelf {sx1 - sx0:.4f} x {sy1 - sy0:.4f} with {len(LEGS)} notches", SH is not None and near(SH["width"], sx1 - sx0) and near(SH["depth"], sy1 - sy0))
else:
    check("no shelf", SH is None)


# ---- cut files
def readdxf(name):
    doc = ezdxf.readfile(HERE / name)
    ok = doc.dxfversion == "AC1009" and doc.header.get("$INSUNITS", 1) == 1 and not doc.audit().has_errors
    return doc.modelspace(), ok


def polys(msp):
    out = []
    for e in msp:
        if e.dxf.layer != "CUT":
            continue
        if e.dxftype() == "POLYLINE":
            out.append(([(v.dxf.location[0], v.dxf.location[1]) for v in e.vertices], e.is_closed))
        elif e.dxftype() == "LWPOLYLINE":
            out.append(([(x, y) for x, y, *_ in e.get_points()], e.closed))
    return out


def area(pts):
    return abs(sum(a[0] * b[1] - b[0] * a[1] for a, b in zip(pts, pts[1:] + pts[:1]))) / 2


def bbox(pts):
    xs, ys = [p[0] for p in pts], [p[1] for p in pts]
    return min(xs), min(ys), max(xs), max(ys)


# A laser outline: a sharp polygon of square corners, counter-clockwise, with a radius at chosen corners and a relief
# circle centred on others. Expected as LINE and ARC entities; its area from the polygon and the corner pieces.
def outline_parts(pts, radii, dx=0.0, dy=0.0):
    """radii[i] = (r, relief). Returns (lines, arcs): lines as frozensets of two points, arcs as (cx, cy, r, start, end) in degrees, CCW"""
    n = len(pts)
    ends = []
    for i in range(n):
        p, a_, c_ = pts[i], pts[i - 1], pts[(i + 1) % n]
        l1, l2 = math.dist(a_, p), math.dist(p, c_)
        d1 = ((p[0] - a_[0]) / l1, (p[1] - a_[1]) / l1)
        d2 = ((c_[0] - p[0]) / l2, (c_[1] - p[1]) / l2)
        turn = d1[0] * d2[1] - d1[1] * d2[0]
        r, relief = radii[i]
        if r <= 0:
            ends.append((p, p, None))
            continue
        s_ = (p[0] - d1[0] * r, p[1] - d1[1] * r)
        e_ = (p[0] + d2[0] * r, p[1] + d2[1] * r)
        cen = p if relief else (p[0] + (d2[0] - d1[0]) * r, p[1] + (d2[1] - d1[1]) * r)
        ccw = (not relief) and turn > 0
        ang = lambda q: math.degrees(math.atan2(q[1] - cen[1], q[0] - cen[0])) % 360
        st, en = (ang(s_), ang(e_)) if ccw else (ang(e_), ang(s_))
        ends.append((s_, e_, (cen[0] + dx, cen[1] + dy, r, st, en)))
    lines, arcs = [], []
    for i in range(n):
        _, e_, arc = ends[i]
        s2 = ends[(i + 1) % n][0]
        if arc:
            arcs.append(arc)
        if math.dist(e_, s2) > 1e-9:
            lines.append(((e_[0] + dx, e_[1] + dy), (s2[0] + dx, s2[1] + dy)))
    return lines, arcs


def outline_area(pts, radii):
    a = area(pts)
    n = len(pts)
    for i in range(n):
        r, relief = radii[i]
        if r <= 0:
            continue
        p, a_, c_ = pts[i], pts[i - 1], pts[(i + 1) % n]
        turn = (p[0] - a_[0]) * (c_[1] - p[1]) - (p[1] - a_[1]) * (c_[0] - p[0])
        a += -0.75 * math.pi * r * r if relief else (-1 if turn > 0 else 1) * (1 - math.pi / 4) * r * r
    return a


def rect_outline(x0, y0, x1, y1, r):
    return [(x0, y0), (x1, y0), (x1, y1), (x0, y1)], [(r, False)] * 4


def rib_outline(length, slots, from_top, tabs):
    """the rib's laser outline (u along it, v up from its bottom edge), counter-clockwise, and each corner's radius"""
    e = 1e-9
    cuts = [(max(0.0, c - SW / 2), min(length, c + SW / 2)) for c in slots]
    bot, top = ([], cuts) if from_top else (cuts, [])
    pts = [(0.0, SD) if bot and bot[0][0] <= e else (0.0, 0.0)]
    for a_, b_ in bot:
        if a_ > e:
            pts += [(a_, 0.0), (a_, SD)]
        pts.append((b_, SD))
        if b_ < length - e:
            pts.append((b_, 0.0))
    if not (bot and bot[-1][1] >= length - e):
        pts.append((length, 0.0))
    pts.append((length, RH - SD) if top and top[-1][1] >= length - e else (length, RH))
    feats = sorted([(a_, (a_, b_)) for a_, b_ in top] + [(c, None) for c in tabs], key=lambda f: -f[0])
    roots = set()
    for at, cut in feats:
        if cut:
            a_, b_ = cut
            if b_ < length - e:
                pts.append((b_, RH))
            pts += [(b_, RH - SD), (a_, RH - SD)]
            if a_ > e:
                pts.append((a_, RH))
        else:
            h = TAB_L / 2
            pts += [(at + h, RH), (at + h, RH + TP), (at - h, RH + TP), (at - h, RH)]
            roots |= {(round(at + h, 6), round(RH, 6)), (round(at - h, 6), round(RH, 6))}
    if not (top and top[0][0] <= e):
        pts.append((0.0, RH))
    clean = [q for i, q in enumerate(pts) if abs(q[0] - pts[i - 1][0]) + abs(q[1] - pts[i - 1][1]) > e]
    edges = [c + d for c in slots for d in (-SW / 2, SW / 2)]
    radii = []
    for u, v in clean:
        if (round(u, 6), round(v, 6)) in roots:
            radii.append((R_RELIEF, True))
        elif abs(v - (RH + TP)) < 1e-6:
            radii.append((R_RIB, False))
        elif (bot and abs(v - SD) < 1e-6) or (top and abs(v - (RH - SD)) < 1e-6) or any(abs(u - x) < 1e-6 for x in edges):
            radii.append((R_SLOT, False))
        else:
            radii.append((R_RIB, False))
    return clean, radii


def found_parts(msp, keep=lambda x, y: True):
    lines, arcs = [], []
    for e in msp:
        if e.dxf.layer != "CUT":
            continue
        if e.dxftype() == "LINE":
            a_, b_ = (e.dxf.start[0], e.dxf.start[1]), (e.dxf.end[0], e.dxf.end[1])
            if keep(*a_):
                lines.append((a_, b_))
        elif e.dxftype() == "ARC":
            c = e.dxf.center
            if keep(c[0], c[1]):
                arcs.append((c[0], c[1], e.dxf.radius, e.dxf.start_angle % 360, e.dxf.end_angle % 360))
    return lines, arcs


def same_parts(found, want):
    fl, fa = found
    wl, wa = want
    pt = lambda p, q: near(p[0], q[0]) and near(p[1], q[1])
    line_eq = lambda l1, l2: (pt(l1[0], l2[0]) and pt(l1[1], l2[1])) or (pt(l1[0], l2[1]) and pt(l1[1], l2[0]))
    adiff = lambda a_, b_: min(abs(a_ - b_), 360 - abs(a_ - b_))
    arc_eq = lambda a1, a2: near(a1[0], a2[0]) and near(a1[1], a2[1]) and near(a1[2], a2[2]) and adiff(a1[3], a2[3]) < 0.05 and adiff(a1[4], a2[4]) < 0.05
    return (len(fl) == len(wl) and len(fa) == len(wa) and all(any(line_eq(a_, b_) for b_ in fl) for a_ in wl)
            and all(any(arc_eq(a_, b_) for b_ in fa) for a_ in wa))


def same_corners(found, want):
    found = [p for i, p in enumerate(found) if not (i == len(found) - 1 and near(p[0], found[0][0]) and near(p[1], found[0][1]))]
    return len(found) == len(want) and all(any(near(a[0], b[0]) and near(a[1], b[1]) for b in found) for a in want) \
        and all(any(near(a[0], b[0]) and near(a[1], b[1]) for b in want) for a in found)


F = manifest["files"]
msp, ok = readdxf(F["topPlate"])
check("top plate DXF: R12, inches, no audit errors", ok)
TOP_PTS, TOP_R = rect_outline(0, 0, L, W, R_TOP)
check(f"top plate outline {L:.3f} x {W:.3f} at the origin, corners R{R_TOP}", same_parts(found_parts(msp), outline_parts(TOP_PTS, TOP_R)))
circles = [e for e in msp if e.dxftype() == "CIRCLE" and e.dxf.layer == "CUT"]
if SPEC:
    grid = {(round(x, 3), round(y, 3)) for x in HX for y in HY}
    found = {(round(c.dxf.center[0], 3), round(c.dxf.center[1], 3)) for c in circles}
    check(f"{len(grid)} holes dia {D:.4f} at the grid points", len(circles) == len(grid) and found == grid and all(near(c.dxf.radius, D / 2) for c in circles),
          f"{len(circles)} circles")
else:
    check("no holes in a plain top", not circles)
want_slots = []
for x, y, along in TAB_SLOTS:
    a_, b_ = (SLOT_LEN / 2, SLOT_WID / 2) if along == "x" else (SLOT_WID / 2, SLOT_LEN / 2)
    want_slots.append((x - a_, y - b_, x + a_, y + b_))
got_slots = [bbox(q) for q, c in polys(msp) if c and len(q) in (4, 5) and near(area(q), SLOT_LEN * SLOT_WID, 0.001)]
check(f"{len(want_slots)} tab slots cut in the top where the tabs come up",
      len(got_slots) == len(want_slots) == len(polys(msp)) and all(any(all(near(p_, q_) for p_, q_ in zip(w_, g_)) for g_ in got_slots) for w_ in want_slots),
      f"{len(got_slots)} slots")

msp, ok = readdxf(F["ribs"])
check("ribs DXF: R12, inches, no audit errors", ok)
LONG_Y = RH + TP + 2
C_PTS, C_R = rib_outline(CROSS_LEN, CROSS_SLOTS, True, CROSS_TABS)
L_PTS, L_R = rib_outline(LONG_LEN, LONG_SLOTS, False, LONG_TABS)
split = RH + TP + 1
check(f"cross rib {CROSS_LEN:.4f} x {RH} at y 0: slots from the top, {len(CROSS_TABS)} tabs, every line and arc in place",
      same_parts(found_parts(msp, lambda x, y: y < split), outline_parts(C_PTS, C_R)))
check(f"long rib {LONG_LEN:.4f} x {RH} at y {LONG_Y:.3f}: slots from the bottom, {len(LONG_TABS)} tabs, every line and arc in place",
      same_parts(found_parts(msp, lambda x, y: y > split), outline_parts(L_PTS, L_R, 0, LONG_Y)))
check("ribs DXF holds nothing else", not polys(msp) and not [e for e in msp if e.dxftype() == "CIRCLE"])

msp, ok = readdxf(F["plates"])
check("plates DXF: R12, inches, no audit errors", ok)
PL_PTS, PL_R = rect_outline(0, 0, END, END, R_PLATE)
cs = [e for e in msp if e.dxftype() == "CIRCLE"]
check(f"cap and base plates {END:.3f} square, corners R{R_PLATE}, 2 apart, dia {FOOT_HOLE} hole centred in the base",
      same_parts(found_parts(msp, lambda x, y: x < END + 1), outline_parts(PL_PTS, PL_R))
      and same_parts(found_parts(msp, lambda x, y: x > END + 1), outline_parts(PL_PTS, PL_R, END + 2, 0))
      and len(cs) == 1 and near(cs[0].dxf.radius, FOOT_HOLE / 2) and near(cs[0].dxf.center[0], END + 2 + END / 2) and near(cs[0].dxf.center[1], END / 2))
if SHELF_T > 0:
    msp, ok = readdxf(F["shelf"])
    sp = polys(msp)
    check(f"shelf DXF: one closed outline, area {shelf_area:.3f}, every notch corner in place",
          ok and len(sp) == 1 and sp[0][1] and near(area(sp[0][0]), shelf_area, 0.01) and same_corners(sp[0][0], SHELF_CORNERS),
          f"{len(sp)} outlines")

# ---- design rules
nut_ac = NUT_AF / math.cos(math.pi / 6)
rules = {
    "rib": RH >= 6 * RT and RT <= TP + 0.125 + 1e-9,
    "spacing": gap_x <= 24 + 1e-9 and gap_y <= 24 + 1e-9,
    "overhang": 1 - 1e-9 <= over_x <= 6 + 1e-9 and 1 - 1e-9 <= over_y <= 6 + 1e-9,
    "holes": (not SPEC) or slot_min >= 0.125 - 1e-9,
    "crate": len(XS) >= 2 and len(YS) >= 2 and RH / 2 >= 1,
    "legs": LEG_LEN >= 12,
    "shelf": SHELF_H - RAIL >= FOOT_H + PLATE_T + 2 and SHELF_H <= Z_RIB - PLATE_T - 8,
    "nut": LEG - 2 * LEGW >= nut_ac + 0.0625,
    "rail": RAIL <= LEG,
    "tabs": min(b - a for v in (XS, YS) for a, b in zip(v, v[1:])) - SW >= TAB_L + 1 - 1e-9,
}
for k, v in rules.items():
    check(f"design rule {k}", v)
mc = {c["id"]: c["ok"] for c in manifest["checks"]}
check("manifest's own design checks agree with these", mc == rules, f"manifest {mc}")

# ---- weights
area_t = lambda b, w: b * b - (b - 2 * w) ** 2 - (4 - math.pi) * ((2 * w) ** 2 - w ** 2)   # A500 corners: outside radius 2 x wall, inside 1 x wall
n_holes = len(HX) * len(HY)
w_top = (outline_area(TOP_PTS, TOP_R) - (n_holes * math.pi * (D / 2) ** 2 if SPEC else 0) - len(TAB_SLOTS) * SLOT_LEN * SLOT_WID) * TP * STEEL
w_ribs = (len(XS) * outline_area(C_PTS, C_R) + len(YS) * outline_area(L_PTS, L_R)) * RT * STEEL
w_legs = len(LEGS) * LEG_LEN * area_t(LEG, LEGW) * STEEL
w_rails = (sum(2 * (b - LEG) for b in bays) + len(legx) * (legy[1] - legy[0] - LEG)) * area_t(RAIL, RAILW) * STEEL
w_shelf = shelf_area * SHELF_T * STEEL
w_plates = len(LEGS) * (2 * outline_area(PL_PTS, PL_R) - math.pi * (FOOT_HOLE / 2) ** 2) * PLATE_T * STEEL
wt = manifest["weight"]
check(f"weights: top {w_top:.2f}, ribs {w_ribs:.2f}, legs {w_legs:.2f}, stretchers {w_rails:.2f}, shelf {w_shelf:.2f}, plates {w_plates:.2f} lb",
      near_w(wt["top"], w_top) and near_w(wt["ribs"], w_ribs) and near_w(wt["legs"], w_legs) and near_w(wt["rails"], w_rails)
      and (near_w(wt["shelf"], w_shelf) if SHELF_T > 0 else wt["shelf"] == 0) and near_w(wt["plates"], w_plates)
      and near_w(wt["total"], w_top + w_ribs + w_legs + w_rails + w_shelf + w_plates), f"manifest {wt}")
print("ALL CHECKS PASSED" if not bad else f"{bad} CHECK(S) FAILED")
sys.exit(1 if bad else 0)
