#!/usr/bin/env python3
"""Check the welding cart 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-cart.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.

  * frame (square tube b, A500 corners: outside radius 2 x wall), L corners mitred 45 degrees, lengths long point to long point:
    bottom frame Lb x W with Lb = Ls + D + 2c + b, c = 1/2; side rails and the front and rear end rails
    mitred at the four corners, the bay rail butted between the side rails under the rear posts (x = Ls - b .. Ls);
    frame underside at caster mount height + 1/4 pad, bottle floor on top of it (sheet thickness t);
  * top frame under the top shelf: top at H - t, underside H - t - b; front posts from the bottom
    frame up to it, rear posts up to the handle top Hh; handle underside Hh - b;
  * bay: clear width W - 2b >= n D + (n + 1) c; bottles at equal gaps across, 1/2 from the chain-bar posts;
    the rear stop D + 2c behind the posts, then 3 of hand room to the handle at the rear end (uprights on
    the side rails' rear ends, up to Hh): Lb = Ls + D + 2c + 3 + b; the grip clear between the uprights at
    least 5; the hand room is read back from the floor plate DXF and the manifest's rear stop;
  * crossbars: the upper bar centre wanted at 2/3 of the bottle height above the bottle floor, held
    2 under the handle; the lower at 1/4; a bar within 2 of the top frame (tube to tube) moves onto
    it; then upper 60 % up to the shoulder, lower 20 to 35 %, bars 2 apart, lower eyes 1/4 above the 2 in stops;
  * chain eyes 1/4 x 1 x 1, standing out 1 behind the bars, 1/2 inside each bottle's edge, at least
    1/8 clear of the bottle;
  * plates: top shelf Ls x W with notches 1/4 clear round the rear posts; bottom shelf (if any) from
    the front to 1/16 short of the bay rail's centre line, notched round all four posts; bottle floor
    from 1/16 past that line to the rear, notched round the rear posts; every notch 1/4 clear of its
    post on both sides;
  * stops 1/4 x 2: rear W - 2b + 1/2 long, sides from 1/4 behind the posts to the rear stop;
  * caster pads: tube + caster plate each way, outside edges flush; the caster bolt pattern centred
    on the caster plate in the open corner; every bolt at least half the nut across corners + 1/32
    clear of every bottom frame tube; pad no wider than half the frame;
  * caster bolts: a bolt centre at least the larger of the USS washer radius and half the nut across
    corners, plus the 1/4 fillet leg of the pad-to-tube weld, plus 1/32, from every bottom frame tube
    (the caster plate moves in from the tube face and the pad grows by it), holes at least 1.5 bolt
    diameters from the pad edges; bolt length washer + 1/4 caster plate + pad + nut + 1/8, rounded up
    to 1/4, its tail above the pad 1/8 under the tube height;
  * the upper bar at most at the bottle shoulder, taken as 80 % of the height to the valve top;
  * cut files: DXF R12, inches stated in the file, no audit errors, exactly the outlines and holes of the
    part and nothing else on any layer; every outline corner where the rules put it, every hole where
    the bolt pattern puts it;
  * the drawing set DXF, read row by row whatever its language: every parts-list and cut-list row carries
    its mark, quantity and length on one line, each tip angle sits in its own row and column, and the chain
    bar centre lines, the wheelbase and the track are on the views; the handle uprights' foot gussets;
  * weights (steel 0.2836 lb/in3, within 0.5 %), the centre of gravity and the advisory tip angles
    (casters and chain not counted; machine at the middle of its box, bottles at half height), loaded,
    bottles without the machine, and empty.

Exit status 0 and "ALL CHECKS PASSED" when everything holds.
"""
import json
import math
import re
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
C, NOTCH, SPLIT, STOP_T, STOP_H, PAD_T = 0.5, 0.25, 0.125, 0.25, 2.0, 0.25
EYE_T, EYE_OUT, EYE_H, EYE_HOLE, EYE_IN, EYE_CLR = 0.25, 1.0, 1.0, 0.5, 0.5, 0.125
BAR_GAP, MIN_POST, HANDLE_OVER = 2.0, 6.0, 2.0
# bolt: clearance hole, nut across flats, nut height, USS washer OD and thickness, nominal diameter
# ... and the split lock washer thickness
BOLTS = {"5/16": (0.34375, 0.5, 0.2656, 0.875, 0.083, 0.3125, 0.078), "3/8": (0.40625, 0.5625, 0.3281, 1.0, 0.083, 0.375, 0.094)}
FILLET, CASTER_PLATE_T, EDGE_D, SHOULDER = 0.25, 0.25, 1.5, 0.8
manifest = json.loads((HERE / "manifest.json").read_text())
I = manifest["inputs"]
W, LS, H, HH = I["frameWidth"], I["topShelfLength"], I["topShelfHeight"], I["handleHeight"]
N, D, HB = I["bottles"], I["bottleDiameter"], I["bottleHeightToValveTop"]
B, WALL, T, BOTTOM = I["tube"]["size"], I["tube"]["wall"], I["sheet"], I["bottomShelf"]
CA = I["caster"]
WHEEL, MOUNT, PL, PW, BL, BW, BOLT = CA["wheel"], CA["mountHeight"], CA["plateAlong"], CA["plateAcross"], CA["boltsAlong"], CA["boltsAcross"], CA["bolt"]
M = I["machine"]
MW, MD, MH, MLB, BLB = M["width"], M["depth"], M["height"], M["weight"], I["fullBottleWeight"]

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, tol=TOL):
    return a is not None and len(a) == len(b) and all(near(x, y, tol) for x, y in zip(a, b))


check("inputs inside the generator's ranges",
      16 <= W <= 36 and 18 <= LS <= 40 and 24 <= H <= 40 and 30 <= HH <= 50 and N in (1, 2) and 5 <= D <= 10 and 18 <= HB <= 62
      and 3 <= WHEEL <= 8 and 3.5 <= MOUNT <= 10 and 2.5 <= PL <= 6 and 2.5 <= PW <= 6 and 1.5 <= BL <= 5.5 and 1.5 <= BW <= 5.5
      and 6 <= MW <= 36 and 6 <= MD <= 40 and 6 <= MH <= 40 and 10 <= MLB <= 400 and 5 <= BLB <= 200 and BOLT in BOLTS,
      f"inputs {I}")

# ---- frame and levels
HAND, GRIP_MIN = 3.0, 5.0
GUS = max(4.0, math.ceil(2.5 * B * 2 - 1e-9) / 2)   # foot gusset legs
X_STOP = LS + D + 2 * C          # the rear stop's inside face: a bottle pushed back stops here
BAY = D + 2 * C + HAND + B
LB = LS + BAY
ZB0 = MOUNT + PAD_T
ZB1 = ZB0 + B
ZF = ZB1 + T
ZT1 = H - T
ZT0 = ZT1 - B
ZTC = (ZT0 + ZT1) / 2
ZH0 = HH - B
FRONT_POST, REAR_POST = ZT0 - ZB1, HH - ZB1
# rear running gear (owner 16.11): 8 in wheels when the frame underside is 5 in up or more, else 6 in; the axle a wheel
# radius ahead of the rear face and a radius up; the wheel centre outside the rail face by the plate, a washer and half a tyre
RW_W, AXLE, AXLE_HOLE, RW_WASHER_T, BOSS, PIN_D, PIN_OVER, ROUND = 1.75, 0.625, 0.65625, 0.0625, 1.25, 0.15625, 0.375, 0.5
RD = 8.0 if ZB0 >= 5 - 1e-9 else 6.0
XA, ZA = LB - RD / 2, RD / 2
YW = 0.25 + RW_WASHER_T + RW_W / 2
AXLE_LEN = W + 2 * (YW + RW_W / 2 + RW_WASHER_T + PIN_OVER)


def round_corners(pts, r, seg=6):
    out = []
    n = len(pts)
    for i in range(n):
        p, a, c = pts[i], pts[i - 1], pts[(i + 1) % n]
        ux, uy, vx, vy = a[0] - p[0], a[1] - p[1], c[0] - p[0], c[1] - p[1]
        lu, lv = math.hypot(ux, uy), math.hypot(vx, vy)
        ux, uy, vx, vy = ux / lu, uy / lu, vx / lv, vy / lv
        th = math.acos(max(-1.0, min(1.0, ux * vx + uy * vy)))
        d = min(r / math.tan(th / 2), lu / 2, lv / 2)
        rr = d * math.tan(th / 2)
        t1, t2 = (p[0] + ux * d, p[1] + uy * d), (p[0] + vx * d, p[1] + vy * d)
        bx, by = ux + vx, uy + vy
        bl, h = math.hypot(bx, by), rr / math.sin(th / 2)
        cx, cy = p[0] + bx / bl * h, p[1] + by / bl * h
        a1, a2 = math.atan2(t1[1] - cy, t1[0] - cx), math.atan2(t2[1] - cy, t2[0] - cx)
        da = a2 - a1
        while da > math.pi:
            da -= 2 * math.pi
        while da < -math.pi:
            da += 2 * math.pi
        out += [(cx + rr * math.cos(a1 + da * k / seg), cy + rr * math.sin(a1 + da * k / seg)) for k in range(seg + 1)]
    return out


AXLE_PLATE = round_corners([(LB - GUS - 2, ZB1), (LB, ZB0 + GUS + 1), (LB, ZA), (XA + BOSS, ZA - BOSS), (XA - BOSS, ZA - BOSS), (LB - GUS - 2, ZB0)], ROUND)
fr, lv = manifest["frame"], manifest["levels"]
check(f"frame {LB:.4f} x {W:.4f} outside, bay {BAY:.4f} (D + 2c + 3 hand room + b)", near(fr["length"], LB) and near(fr["bay"], BAY))
check(f"levels: frame {ZB0:.4f} to {ZB1:.4f}, bottle floor {ZF:.4f}, top frame {ZT0:.4f} to {ZT1:.4f}, handle underside {ZH0:.4f}",
      near(lv["frameUnderside"], ZB0) and near(lv["frameTop"], ZB1) and near(lv["bottleFloor"], ZF) and near(lv["topFrameUnderside"], ZT0)
      and near(lv["topFrameTop"], ZT1) and near(lv["handleUnderside"], ZH0))
check(f"posts: front {FRONT_POST:.4f}, rear {REAR_POST:.4f}", near(fr["frontPost"], FRONT_POST) and near(fr["rearPost"], REAR_POST))


# ---- crossbars
def frame_gap(z):
    return z - B / 2 - ZT1 if z - B / 2 >= ZT1 else ZT0 - (z + B / 2)


def place(want, top):
    z, held = ZF + want * HB, False
    if z > top:
        z, held = top, True
    on = False
    if frame_gap(z) < BAR_GAP - 1e-9:
        z, on = ZTC, True
    return z, on, (z - ZF) / HB, held


UP = place(2 / 3, ZH0 - BAR_GAP - B / 2)
LO = place(0.25, float("inf"))
bars = {b["bar"]: b for b in manifest["bars"]}
for name, (z, on, pct, held) in (("lower", LO), ("upper", UP)):
    m = bars.get(name)
    check(f"{name} bar centre {z:.4f} ({pct * 100:.1f} % of the bottle){' on the top frame' if on else ''}",
          m is not None and near(m["centre"], z) and m["onTopFrame"] == on and near(m["ofBottle"], pct, 1e-4) and m["heldUnderHandle"] == held, f"manifest {m}")

# ---- bottles and eyes
WC = W - 2 * B
GAP = (WC - N * D) / (N + 1)
XB = LS + C + D / 2
BOT = [(XB, B + GAP + D / 2 + i * (D + GAP)) for i in range(N)]
check(f"{N} bottle(s) at y = {', '.join(f'{y:.3f}' for _, y in BOT)}, x = {XB:.3f}",
      len(manifest["bottles"]) == N and all(near(a[0], b[0]) and near(a[1], b[1]) for a, b in zip(manifest["bottles"], BOT)))
EYES = [e for _, y in BOT for e in (y - D / 2 + EYE_IN, y + D / 2 - EYE_IN)]
eye_clear = min(math.hypot(max(0.0, x - (LS + EYE_OUT)), max(0.0, abs(e - y) - EYE_T / 2)) - D / 2 for x, y in BOT for e in EYES)
ME = manifest["eyes"]
check(f"chain eyes at y = {', '.join(f'{e:.3f}' for e in EYES)} on both bars, {eye_clear:.4f} clear of the bottles",
      lists_near(ME["across"], EYES) and ME["total"] == 2 * len(EYES) and near(ME["nearestToBottle"], eye_clear))


# ---- plates
def notch(x0, x1, y0, y1):
    return (x0, x1, y0, y1)


SPL = LS - B / 2
TOP = (0.0, LS, 0.0, W, [notch(LS - B - NOTCH, LS, 0, B + NOTCH), notch(LS - B - NOTCH, LS, W - B - NOTCH, W)])
BX1 = SPL - SPLIT / 2
BOTP = (0.0, BX1, 0.0, W, [notch(0, B + NOTCH, 0, B + NOTCH), notch(0, B + NOTCH, W - B - NOTCH, W),
                           notch(LS - B - NOTCH, BX1, 0, B + NOTCH), notch(LS - B - NOTCH, BX1, W - B - NOTCH, W)]) if BOTTOM else None
FX0 = SPL + SPLIT / 2
FLOOR = (FX0, LB, 0.0, W, [notch(FX0, LS + NOTCH, 0, B + NOTCH), notch(FX0, LS + NOTCH, W - B - NOTCH, W),
                           notch(LB - B - NOTCH, LB, 0, B + NOTCH), notch(LB - B - NOTCH, LB, W - B - NOTCH, W)])
POSTS = [(0, B, 0, B), (0, B, W - B, W), (LS - B, LS, 0, B), (LS - B, LS, W - B, W)]
UPRIGHTS = [(LB - B, LB, 0, B), (LB - B, LB, W - B, W)]


def notch_clear(plate, posts):
    """Every post that passes through the plate sits inside a notch with 1/4 clear on its open sides, and no post is left uncovered."""
    x0, x1, y0, y1, ns = plate
    ok = True
    for p in posts:
        if p[1] <= x0 + 1e-9 or p[0] >= x1 - 1e-9:
            continue
        p = (max(p[0], x0), min(p[1], x1), max(p[2], y0), min(p[3], y1))  # the part of the post the plate reaches
        hit = [n for n in ns if n[0] <= p[0] + 1e-9 and n[1] >= p[1] - 1e-9 and n[2] <= p[2] + 1e-9 and n[3] >= p[3] - 1e-9]
        if len(hit) != 1:
            ok = False
            continue
        n = hit[0]
        for edge_n, edge_p, plate_edge, sign in ((n[0], p[0], x0, -1), (n[1], p[1], x1, 1), (n[2], p[2], y0, -1), (n[3], p[3], y1, 1)):
            if abs(edge_n - plate_edge) < 1e-9:
                continue  # open to the plate edge
            if not near((edge_n - edge_p) * sign, NOTCH, 1e-6):
                ok = False
    return ok


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 plate_area(plate):
    x0, x1, y0, y1, ns = plate
    return (x1 - x0) * (y1 - y0) - sum((n[1] - n[0]) * (n[3] - n[2]) for n in ns)


def plate_corners(plate):
    """Corners of the outline (front left corner of the plate at the origin), from the notch rectangles."""
    x0, x1, y0, y1, ns = plate
    corners = {(x0, y0), (x1, y0), (x1, y1), (x0, y1)}
    for n in ns:
        box = {(n[0], n[2]), (n[1], n[2]), (n[1], n[3]), (n[0], n[3])}
        taken = {c for c in corners if n[0] - 1e-9 <= c[0] <= n[1] + 1e-9 and n[2] - 1e-9 <= c[1] <= n[3] + 1e-9}
        corners = (corners - taken) | box
    corners = {c for c in corners if not ((near(c[0], x0, 1e-6) or near(c[0], x1, 1e-6)) and (near(c[1], y0, 1e-6) or near(c[1], y1, 1e-6)))
               or not any(n[0] - 1e-9 <= c[0] <= n[1] + 1e-9 and n[2] - 1e-9 <= c[1] <= n[3] + 1e-9 for n in ns)}
    return {(round(x - x0, 4), round(y - y0, 4)) for x, y in corners}


PM = manifest["plates"]
# the front posts end under the top frame: only the rear posts pass through the top shelf
for key, plate, label, posts in (("top", TOP, "top shelf", POSTS[2:]), ("bottom", BOTP, "bottom shelf", POSTS), ("floor", FLOOR, "bottle floor", POSTS + UPRIGHTS)):
    m = PM.get(key)
    if plate is None:
        check(f"no {label}", m is None)
        continue
    x0, x1, y0, y1, ns = plate
    check(f"{label} {x1 - x0:.4f} x {y1 - y0:.4f} at x {x0:.4f}, {len(ns)} notches 1/4 clear of the posts",
          m is not None and near(m["length"], x1 - x0) and near(m["width"], y1 - y0) and near(m["origin"][0], x0)
          and len(m["notches"]) == len(ns) and all(lists_near(a, list(b)) for a, b in zip(m["notches"], ns)) and notch_clear(plate, posts))

# ---- stops
REAR_LEN = W - 2 * B + 2 * STOP_T
SIDE_LEN = X_STOP - (LS + NOTCH)
ST = manifest["stops"]
check(f"stops: rear {REAR_LEN:.4f}, two sides {SIDE_LEN:.4f}, inside faces on the frame's", near(ST["rear"]["length"], REAR_LEN) and near(ST["side"]["length"], SIDE_LEN) and ST["side"]["qty"] == 2
      and near(ST["rear"]["at"][0], X_STOP) and near(ST["side"]["at"][0][3], B) and near(ST["side"]["at"][1][2], W - B))

# ---- caster pads
HOLE, NUT_AF, NUT_H, WASHER_OD, WASHER_T, BOLT_D, LOCK_T = BOLTS[BOLT]
NUT_NEED = max(WASHER_OD / 2, NUT_AF / math.cos(math.pi / 6) / 2) + FILLET + 1 / 32


def pad_axis(plate, pattern):
    edge = (plate - pattern) / 2
    gap, extra = max(0.0, NUT_NEED - edge), max(0.0, EDGE_D * BOLT_D - edge)
    return gap, B + gap + plate + extra, B + gap + plate / 2


GAP_L, PAD_L, CX0 = pad_axis(PL, BL)
GAP_W, PAD_W, CY0 = pad_axis(PW, BW)
PAD_HOLES = [(CX0 + i * BL / 2, CY0 + j * BW / 2) for i, j in ((-1, -1), (1, -1), (1, 1), (-1, 1))]
CXF, CXR, CYL, CYR = CX0, XA, CY0, W - CY0      # front casters; the rear contact line is the rear wheels' (x = the axle)
UNDER = LOCK_T + WASHER_T + CASTER_PLATE_T + PAD_T
BOLT_LEN = math.ceil((UNDER + NUT_H + 0.125) * 4 - 1e-9) / 4
BOLT_TAIL = BOLT_LEN - UNDER
ALL_HOLES = [(CXF + i * BL / 2, cy + j * BW / 2) for cy in (CYL, CYR) for i, j in ((-1, -1), (1, -1), (1, 1), (-1, 1))]
TUBES = [(0, LB, 0, B), (0, LB, W - B, W), (0, B, B, W - B), (LS - B, LS, B, W - B), (LB - B, LB, B, W - B)]
hole_min = min(math.hypot(max(t[0] - x, 0, x - t[1]), max(t[2] - y, 0, y - t[3])) for x, y in ALL_HOLES for t in TUBES)
PD = manifest["pads"]
check(f"caster pads {PAD_L:.4f} x {PAD_W:.4f}, holes {BL} x {BW} apart on the caster plate, {GAP_L:.4f} / {GAP_W:.4f} in from the tube faces",
      near(PD["along"], PAD_L) and near(PD["across"], PAD_W) and len(PD["holesFromCorner"]) == 4
      and all(near(a[0], b[0]) and near(a[1], b[1]) for a, b in zip(PD["holesFromCorner"], PAD_HOLES))
      and lists_near(PD["gapTubeToCasterPlate"], [GAP_L, GAP_W]))
check(f"front casters at x {CXF:.4f}, y {CYL:.4f} / {CYR:.4f}; rear wheels {RD:g} in on the axle at x {XA:.4f}, z {ZA:.4f}, y {-YW:.4f} / {W + YW:.4f} (track {W + 2 * YW:.4f})",
      len(PD["casterCentres"]) == 2 and all(near(a[0], b[0]) and near(a[1], b[1]) for a, b in zip(PD["casterCentres"], [(CXF, CYL), (CXF, CYR)]))
      and near(manifest["contact"]["front"], CXF) and near(manifest["contact"]["rear"], XA) and near(manifest["contact"]["left"], CYL) and near(manifest["contact"]["right"], CYR)
      and near(manifest["contact"]["rearLeft"], -YW) and near(manifest["contact"]["rearRight"], W + YW)
      and manifest["rear"]["wheel"] == RD and lists_near(manifest["rear"]["axleCentre"], [XA, ZA]) and near(manifest["rear"]["track"], W + 2 * YW)
      and near(manifest["rear"]["axleLength"], AXLE_LEN), f"manifest {manifest['rear']} {manifest['contact']}")
check(f"bolt centres {hole_min:.4f} from the frame tubes ({NUT_NEED:.4f} for the washer, the nut and the fillet weld)", near(PD["boltCentreToTube"], hole_min))
check(f"caster bolts {BOLT} x {BOLT_LEN}, tail {BOLT_TAIL:.4f} above the pad", PD["bolt"]["size"] == BOLT and near(PD["bolt"]["length"], BOLT_LEN) and near(PD["bolt"]["tailAbovePad"], BOLT_TAIL))

# ---- tubes
XB2 = W - 2 * B
# corners mitred (owner 16.11): L corners 45 degrees, lengths long point to long point; T joints square cut
want_tubes = [("1", 2, LB), ("2", 2, W), ("3", 1, XB2), ("4", 2, ZT1 - ZB0), ("5", 2, REAR_POST), ("6", 2, LS - B), ("7", 1, W), ("8", 1, XB2)]
n_bars = sum(1 for b in (UP, LO) if not b[1])
if n_bars:
    want_tubes.append(("9", n_bars, XB2))
want_tubes += [("10", 1, W), ("11", 2, HH - ZB0), ("12", 1, W)]
got = [(t["mark"], t["qty"], t["length"]) for t in manifest["tubes"]]
# every corner mitred: three-way at the four bottom corners and the two top front corners (side rails, end rails, front
# posts, top side rails' front ends, top front rail, handle uprights' feet), 45 degrees at the rear post tops and the handle
want_cut = {"1": "corner2", "2": "corner2", "3": "square", "4": "corner2", "5": "mitre1", "6": "corner1", "7": "corner2", "8": "square",
            "9": "square", "10": "mitre2", "11": "cornerMitre", "12": "mitre2"}
check("tube ends: three-way corners at the bottom corners and the top front corners, 45-degree mitres at the rear post tops and the handle, T joints square cut",
      all(t.get("cut") == want_cut[t["mark"]] for t in manifest["tubes"]), f"manifest {[(t['mark'], t.get('cut')) for t in manifest['tubes']]}")
check("tube cut list " + ", ".join(f"{m} {q} x {l:.3f}" for m, q, l in want_tubes),
      len(got) == len(want_tubes) and all(a[0] == b[0] and a[1] == b[1] and near(a[2], b[2]) for a, b in zip(got, want_tubes)), f"manifest {got}")


# ---- cut files
def readdxf(name, extent=None):
    """R12, no audit errors, inches stated in the file (an explicit $INSUNITS 1 and the writer's units=in comment, not a
    default), and the drawing extents those of the part in inches (a millimetre file would be 25.4 times bigger)."""
    doc = ezdxf.readfile(HERE / name)
    raw = (HERE / name).read_text(errors="replace")
    ok = doc.dxfversion == "AC1009" and "$INSUNITS" in doc.header and doc.header["$INSUNITS"] == 1 and "units=in" in raw and not doc.audit().has_errors
    if extent is not None:
        mx = doc.header.get("$EXTMAX")
        ok = ok and mx is not None and near(mx[0], extent[0]) and near(mx[1], extent[1])
    return doc.modelspace(), ok


def inventory(msp):
    """Every entity in the file, as (type, layer, closed): a cut file must hold its outlines and holes and nothing else."""
    out = []
    for e in msp:
        closed = e.is_closed if e.dxftype() == "POLYLINE" else (e.closed if e.dxftype() == "LWPOLYLINE" else None)
        out.append((e.dxftype(), e.dxf.layer, closed))
    return sorted(out, key=str)


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 same_corners(found, want, dx=0.0, dy=0.0):
    found = [(p[0] - dx, p[1] - dy) 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"]
for key, plate, label in (("topShelf", TOP, "top shelf"), ("bottomShelf", BOTP, "bottom shelf"), ("bottleFloor", FLOOR, "bottle floor")):
    if plate is None:
        check(f"no {label} file", F.get(key) is None)
        continue
    msp, ok = readdxf(F[key], (plate[1] - plate[0], plate[3] - plate[2]))
    pl, inv = polys(msp), inventory(msp)
    check(f"{label} DXF: R12, inches, one closed outline and nothing else, area {plate_area(plate):.3f}, every notch corner in place",
          ok and inv == [("POLYLINE", "CUT", True)] and len(pl) == 1 and near(area(pl[0][0]), plate_area(plate), 0.01) and same_corners(pl[0][0], plate_corners(plate)),
          f"{inv}")

msp, ok = readdxf(F["stops"], (max(REAR_LEN, SIDE_LEN), 2 * STOP_H + 2))
sp = sorted(polys(msp), key=lambda q: min(p[1] for p in q[0]))
rect = lambda w, h, dy=0.0: {(0.0, dy), (w, dy), (w, dy + h), (0.0, dy + h)}
check(f"stops DXF: rear {REAR_LEN:.4f} x {STOP_H} at y 0, side {SIDE_LEN:.4f} x {STOP_H} above it, 2 apart, nothing else",
      ok and inventory(msp) == [("POLYLINE", "CUT", True)] * 2 and len(sp) == 2 and same_corners(sp[0][0], rect(REAR_LEN, STOP_H)) and same_corners(sp[1][0], rect(SIDE_LEN, STOP_H, STOP_H + 2)))

EYE_X = PAD_L + 2
msp, ok = readdxf(F["padAndEye"], (EYE_X + EYE_OUT, PAD_W))
pp = sorted(polys(msp), key=lambda q: min(p[0] for p in q[0]))
cs = sorted(((c.dxf.center[0], c.dxf.center[1], c.dxf.radius) for c in msp if c.dxftype() == "CIRCLE" and c.dxf.layer == "CUT"), key=lambda c: (c[0], c[1]))
want_holes = sorted([(x, y, HOLE / 2) for x, y in PAD_HOLES] + [(EYE_X + EYE_OUT / 2, EYE_H / 2, EYE_HOLE / 2)], key=lambda c: (c[0], c[1]))
check(f"pad and eye DXF: pad {PAD_L:.4f} x {PAD_W:.4f} with 4 holes dia {HOLE:.4f} on the bolt pattern, eye {EYE_OUT} x {EYE_H} with dia {EYE_HOLE} centred",
      ok and inventory(msp) == sorted([("CIRCLE", "CUT", None)] * 5 + [("POLYLINE", "CUT", True)] * 2, key=str)
      and len(pp) == 2 and same_corners(pp[0][0], rect(PAD_L, PAD_W)) and same_corners(pp[1][0], {(EYE_X, 0.0), (EYE_X + EYE_OUT, 0.0), (EYE_X + EYE_OUT, EYE_H), (EYE_X, EYE_H)})
      and len(cs) == 5 and all(near(a[0], b[0]) and near(a[1], b[1]) and near(a[2], b[2]) for a, b in zip(cs, want_holes)),
      f"{len(pp)} outlines, {len(cs)} circles")

# ---- the handle: hand room behind a bottle pushed back against the rear stop, and the clear grip
fl = polys(readdxf(F["bottleFloor"])[0])
frame_end = FX0 + max(p[0] for p in fl[0][0]) if fl else None    # the floor plate runs to the frame's rear face
room = frame_end - B - ST["rear"]["at"][0] if frame_end is not None else None
grip = W - 2 * B
HD = manifest["handle"]
check(f"handle at the rear: {room if room is None else round(room, 4)} hand room from the rear stop (in the manifest) to the handle (from the floor plate DXF), {HAND} at least; grip {grip:.4f}, {GRIP_MIN} at least",
      room is not None and room >= HAND - 1e-6 and near(room, LB - B - X_STOP) and near(HD["handRoom"], LB - B - X_STOP) and near(HD["uprightsFrontFace"], LB - B)
      and near(HD["grip"], grip) and grip >= GRIP_MIN and near(HD["uprightLength"], HH - ZB0) and near(HD["top"], HH), f"manifest {HD}")

# ---- the axle plates (1/4 plate, also the handle uprights' foot gussets): outline worked out here, rounded R1/2, the axle hole
AX0, AZ0 = min(p[0] for p in AXLE_PLATE), min(p[1] for p in AXLE_PLATE)
APW, APH = max(p[0] for p in AXLE_PLATE) - AX0, max(p[1] for p in AXLE_PLATE) - AZ0
msp, ok = readdxf(F["axlePlate"], (APW, APH))
ap = polys(msp)
acs = [(c.dxf.center[0], c.dxf.center[1], c.dxf.radius) for c in msp if c.dxftype() == "CIRCLE" and c.dxf.layer == "CUT"]
want_pts = [(x - AX0, z - AZ0) for x, z in AXLE_PLATE]
got_pts = ap[0][0] if ap else []
check(f"axle plate DXF: one closed outline {APW:.3f} x {APH:.3f} (every point as worked out here) and one dia {AXLE_HOLE} hole at ({XA - AX0:.3f}, {ZA - AZ0:.3f})",
      ok and inventory(msp) == sorted([("CIRCLE", "CUT", None), ("POLYLINE", "CUT", True)], key=str) and len(ap) == 1
      and len(got_pts) >= len(want_pts) and all(any(near(g[0], w[0], 0.002) and near(g[1], w[1], 0.002) for g in got_pts) for w in want_pts)
      and len(acs) == 1 and near(acs[0][0], XA - AX0) and near(acs[0][1], ZA - AZ0) and near(2 * acs[0][2], AXLE_HOLE)
      and manifest["rear"]["plate"]["qty"] == 2, f"{inventory(msp)} {acs}")

# ---- design rules
up_ok = 0.6 - 1e-9 <= UP[2] <= min(0.85, SHOULDER) + 1e-9
lo_ok = 0.2 - 1e-9 <= LO[2] <= 0.35 + 1e-9
sep = UP[0] - LO[0] - B if not UP[1] and not LO[1] else float("inf")
rules = {
    "bay": WC >= N * D + (N + 1) * C - 1e-9,
    "machine": MW <= W + 1e-9 and MD <= LS - B - NOTCH + 1e-9,
    "posts": FRONT_POST >= MIN_POST - 1e-9,
    "handle": ZH0 >= H + HANDLE_OVER - 1e-9,
    "upper": up_ok,
    "lower": lo_ok,
    "bars": not (UP[1] and LO[1]) and sep >= BAR_GAP - 1e-9 and LO[0] - EYE_H / 2 >= ZF + STOP_H + 0.25 - 1e-9,
    "eyes": eye_clear >= EYE_CLR - 1e-9,
    "caster": MOUNT >= WHEEL + 0.25 - 1e-9,
    "pattern": BL + HOLE + 0.25 <= PL + 1e-9 and BW + HOLE + 0.25 <= PW + 1e-9,
    "pad": PAD_W <= W / 2 + 1e-9 and 2 * PAD_L <= LB + 1e-9,
    "holes": hole_min >= NUT_NEED - 1e-9,
    "bolt": BOLT_TAIL <= B - 0.125 + 1e-9,
    "grip": LB - B - X_STOP >= HAND - 1e-9 and W - 2 * B >= GRIP_MIN - 1e-9,
    "rear": ZB0 - ZA >= 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, centre of gravity, tip angles
A = B * B - (B - 2 * WALL) ** 2 - (4 - math.pi) * ((2 * WALL) ** 2 - WALL ** 2)   # A500 corners: outside radius 2 x wall, inside 1 x wall
parts = []  # lb, x, y, z


def tube(x0, x1, y0, y1, z0, z1):
    parts.append((max(x1 - x0, y1 - y0, z1 - z0) * A * STEEL, (x0 + x1) / 2, (y0 + y1) / 2, (z0 + z1) / 2))


for y in (0, W - B):
    tube(0, LB, y, y + B, ZB0, ZB1)
for x in (0, LS - B, LB - B):
    tube(x, x + B, B, W - B, ZB0, ZB1)
for y in (0, W - B):
    tube(0, B, y, y + B, ZB1, ZT0)
    tube(LS - B, LS, y, y + B, ZB1, HH)
    tube(0, LS - B, y, y + B, ZT0, ZT1)
for x in (0, LS - B):
    tube(x, x + B, B, W - B, ZT0, ZT1)
for z, on, _, _ in (LO, UP):
    if not on:
        tube(LS - B, LS, B, W - B, z - B / 2, z + B / 2)
tube(LS - B, LS, B, W - B, ZH0, HH)
for y in (0, W - B):
    tube(LB - B, LB, y, y + B, ZB1, HH)
tube(LB - B, LB, B, W - B, ZH0, HH)
w_tubes = sum(p[0] for p in parts)


def plate_mass(plate, z):
    x0, x1, y0, y1, ns = plate
    a = plate_area(plate)
    mx = (x1 - x0) * (y1 - y0) * (x0 + x1) / 2 - sum((n[1] - n[0]) * (n[3] - n[2]) * (n[0] + n[1]) / 2 for n in ns)
    my = (x1 - x0) * (y1 - y0) * (y0 + y1) / 2 - sum((n[1] - n[0]) * (n[3] - n[2]) * (n[2] + n[3]) / 2 for n in ns)
    w = a * T * STEEL
    parts.append((w, mx / a, my / a, z + T / 2))
    return w


w_top = plate_mass(TOP, ZT1)
w_bottom = plate_mass(BOTP, ZB1) if BOTP else 0.0
w_floor = plate_mass(FLOOR, ZB1)
w_stops = 0.0
for r in ((X_STOP, X_STOP + STOP_T, B - STOP_T, W - B + STOP_T), (LS + NOTCH, X_STOP, B - STOP_T, B), (LS + NOTCH, X_STOP, W - B, W - B + STOP_T)):
    w = (r[1] - r[0]) * (r[3] - r[2]) * STOP_H * STEEL
    w_stops += w
    parts.append((w, (r[0] + r[1]) / 2, (r[2] + r[3]) / 2, ZF + STOP_H / 2))
w_pad = (PAD_L * PAD_W - 4 * math.pi * (HOLE / 2) ** 2) * PAD_T * STEEL
for y in (PAD_W / 2, W - PAD_W / 2):        # front pads only: the rear runs on wheels
    parts.append((w_pad, PAD_L / 2, y, MOUNT + PAD_T / 2))
w_eye = (EYE_OUT * EYE_H - math.pi * (EYE_HOLE / 2) ** 2) * EYE_T * STEEL
for z, _, _, _ in (LO, UP):
    for e in EYES:
        parts.append((w_eye, LS + EYE_OUT / 2, e, z))
def shoelace(pts):
    a = cx = cy = 0.0
    for i, p in enumerate(pts):
        q = pts[(i + 1) % len(pts)]
        k = p[0] * q[1] - q[0] * p[1]
        a += k
        cx += (p[0] + q[0]) * k
        cy += (p[1] + q[1]) * k
    return abs(a) / 2, cx / (3 * a), cy / (3 * a)


ap_area, ap_cx, ap_cz = shoelace(AXLE_PLATE)
w_ap = (ap_area - math.pi * (AXLE_HOLE / 2) ** 2) * 0.25 * STEEL
for y in (-0.125, W + 0.125):
    parts.append((w_ap, ap_cx, y, ap_cz))
w_axle = math.pi * (AXLE / 2) ** 2 * AXLE_LEN * STEEL
parts.append((w_axle, XA, W / 2, ZA))
total = sum(p[0] for p in parts)
wt = manifest["weight"]
check(f"weights: tubes {w_tubes:.2f}, top {w_top:.2f}, bottom {w_bottom:.2f}, floor {w_floor:.2f}, stops {w_stops:.2f}, pads {2 * w_pad:.2f}, eyes {w_eye * 2 * len(EYES):.2f}, axle plates {2 * w_ap:.2f}, axle {w_axle:.2f}, total {total:.2f} lb",
      near_w(wt["tubes"], w_tubes) and near_w(wt["top"], w_top) and (near_w(wt["bottom"], w_bottom) if BOTP else wt["bottom"] == 0) and near_w(wt["floor"], w_floor)
      and near_w(wt["stops"], w_stops) and near_w(wt["pads"], 2 * w_pad) and near_w(wt["eyes"], w_eye * 2 * len(EYES)) and near_w(wt["axlePlates"], 2 * w_ap)
      and near_w(wt["axle"], w_axle)
      and near_w(wt["total"], total), f"manifest {wt}")


def cog(ps):
    m = sum(p[0] for p in ps)
    return [sum(p[0] * p[i] for p in ps) / m for i in (1, 2, 3)]


MACHINE_X = (LS - B - NOTCH) / 2
empty = cog(parts)
FULL = [(BLB, x, y, ZF + HB / 2) for x, y in BOT]
loaded = cog(parts + [(MLB, MACHINE_X, W / 2, H + MH / 2)] + FULL)
with_bottles = cog(parts + FULL)
CG = manifest["centreOfGravity"]
check(f"centre of gravity empty ({', '.join(f'{v:.3f}' for v in empty)}), loaded ({', '.join(f'{v:.3f}' for v in loaded)}), bottles only ({', '.join(f'{v:.3f}' for v in with_bottles)})",
      lists_near(CG["empty"], empty, 0.01) and lists_near(CG["loaded"], loaded, 0.01) and lists_near(CG["bottlesNoMachine"], with_bottles, 0.01))


SUPPORT = [(CXF, CYL), (XA, -YW), (XA, W + YW), (CXF, CYR)]     # front casters and rear wheels


def tip(g):
    deg = lambda a, h: math.degrees(math.atan2(a, h))

    def dist(a, c):
        ex, ey = c[0] - a[0], c[1] - a[1]
        return abs(ex * (g[1] - a[1]) - ey * (g[0] - a[0])) / math.hypot(ex, ey)
    s0, s1, s2, s3 = SUPPORT
    return {"side": deg(min(dist(s0, s1), dist(s2, s3)), g[2]), "front": deg(dist(s3, s0), g[2]), "rear": deg(dist(s1, s2), g[2])}


TA = manifest["tipAngleAdvisory"]
te, tl, tb = tip(empty), tip(loaded), tip(with_bottles)
check(f"advisory tip angles loaded: sideways {tl['side']:.1f}, to the front {tl['front']:.1f}, to the rear {tl['rear']:.1f} degrees; bottles only {tb['side']:.1f} / {tb['front']:.1f} / {tb['rear']:.1f}; empty {te['side']:.1f} / {te['front']:.1f} / {te['rear']:.1f}",
      all(near(TA["empty"][k], te[k], 0.05) and near(TA["loaded"][k], tl[k], 0.05) and near(TA["bottlesNoMachine"][k], tb[k], 0.05) for k in ("side", "front", "rear")), f"manifest {TA}")

# ---- the drawing set itself: its tables carry the numbers worked out here, row by row (any language: rows are found by
# position, the item mark and quantity, never by their words)
f3 = lambda v: f"{v + 1e-9:.3f}"
f1 = lambda v: f"{v + 1e-9:.1f}"
sdoc = ezdxf.readfile(HERE / F["drawingSet"])
TX = [(e.dxf.text, e.dxf.insert[0], e.dxf.insert[1]) for e in sdoc.modelspace() if e.dxftype() == "TEXT"]


def row_of(t):
    """The texts on the same line as t, left to right, within a table's width of it."""
    return sorted((u for u in TX if abs(u[2] - t[2]) < 0.05 and -40 < u[1] - t[1] < 150), key=lambda u: u[1])


def list_rows(mark, qty):
    """Rows of a table that start with this item mark and quantity: [mark, qty, description, ...]."""
    out = []
    for t in TX:
        if t[0] != mark:
            continue
        r = [u for u in row_of(t) if u[1] >= t[1] - 1e-6]
        if len(r) >= 3 and r[1][0] == str(qty):
            out.append([u[0] for u in r])
    return out


bad_parts, bad_cut = [], []
for mark, qty, length in want_tubes:
    rows = list_rows(mark, qty)
    if not any(r[2].endswith(f"x {f3(length)}") for r in rows):
        bad_parts.append(mark)
    if not any(len(r) == 4 and r[3] == f3(length) for r in rows):
        bad_cut.append(mark)
check("sheet DXF: every parts-list row (mark, quantity, description ending in its length) as worked out here", not bad_parts, f"rows {bad_parts}")
check("sheet DXF: every cut-list row (mark, quantity, length on the same line) as worked out here", not bad_cut, f"rows {bad_cut}")
want_cl = [f"{f3(z - ZB1)} ({f3(z)})" for z, _, _, _ in (LO, UP)]
check("sheet DXF: chain bar centre lines " + ", ".join(want_cl), all(any(t[0].endswith(v) for t in TX) for v in want_cl), "missing")
# tip table: the cells ending in a degree sign, three rows (loaded, bottles only, empty from the top) of three columns
tips = sorted((t for t in TX if re.fullmatch(r"\d+\.\d%%d", t[0])), key=lambda t: (-round(t[2], 1), t[1]))
grid = [[t[0] for t in tips[i:i + 3]] for i in range(0, len(tips), 3)]
want_grid = [[f"{f1(t[k])}%%d" for k in ("side", "front", "rear")] for t in (tl, tb, te)]
check("sheet DXF: the advisory tip angles, each in its row and column", grid == want_grid, f"found {grid}")
want_wt = [f"{f3(XA - CXF)} ", f"{f3(CYR - CYL)} ", f"{f3(W + 2 * YW)} "]
check(f"sheet DXF: wheelbase {want_wt[0].strip()}, front track {want_wt[1].strip()} and rear track {want_wt[2].strip()} on the views",
      all(any(t[0].startswith(v) and len(t[0].split()) >= 2 for t in TX) for v in want_wt), "missing")
print("ALL CHECKS PASSED" if not bad else f"{bad} CHECK(S) FAILED")
sys.exit(1 if bad else 0)
