#!/usr/bin/env python3
"""Check the round-bale feeder package from ruthensystems.com yourself.

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

    pip install ezdxf
    python verify-round-bale-feeder.py

It reads the cut file 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.

  * the ring: 3 or 4 identical sections pinned together; the end posts sit on the circle of the
    rail centre line (radius R); between two neighbouring end posts a 1 in Sch 40 sleeve
    (1.315 OD, 3 long) sits 1/16 clear of each post, so its centre is c = rail OD / 2 + 1.315 / 2 + 1/16
    from each post centre; half joint angle = asin(c / R), a section spans 2 pi / sections - 2 x that
    between its post centres;
  * the rails: three per section, at heights rail OD / 2 (bottom), skirt top and top rail
    (centre lines); "rolled" = an arc of radius R, length R x span; "mitred" = k straight tubes with
    their corners on the circle (mitre turn = span / k), the posts run from the ground to the top rail's top;
    for mitred, k starts at max(2, ceil(R x span / 30)) and goes up (at most 6 more) to the first k
    whose straights, split into m = max(1, ceil(chord / spacing max)) equal openings each,
    give a clear opening of 9 or more (none: the first k); a bar then sits exactly on every corner;
    openings per section = k x m;
  * the bars: straight, all leaning one way at the bar angle, from the mid rail to the top rail;
    rolled: n = max(2, ceil(rail length / spacing max)) openings; spacing p = rail length / n;
    bar j is centred at j x p along the rail centre line, its ends half the horizontal run either
    side; the true length is the 3D distance between the two end points (on the rail axes);
    clear opening = p sin(angle) - bar OD; a corner bar is one whose j x p is a whole number of straights;
  * the copes: at each end the bar meets the rail at angle beta = acos(|d . t|), d the bar's
    direction, t the rail's direction there (rolled: tangent to the circle; mitred: that straight).
    The coped tube's LONG POINT is not in the plane of the two axes. A line along the bar's surface at angle
    phi round it meets the rail at s(phi) = (sqrt(Rr^2 - r^2 sin^2 phi) - r cos phi cos beta) / sin beta
    from the rail axis (Rr rail radius, r bar radius); the long point is where s is smallest, found here
    by scanning phi and refining. Length over the long points = true length - offset at A - offset at B.
    "Copes turned apart" = the angle between the planes (bar, rail at A) and (bar, rail at B).
    Bars of the same kind (corner or not, true length within 0.0005) form a type;
    the manifest's types (mark, qty, corner, lengths, smaller cope angle, copes turned) and each
    bar's type and ends are compared (angles within 0.02 degrees);
  * also from the manifest: rise = distance from the ring centre to the rail centre line at half its
    length - R cos(span / 2); wedgeAtPostClear = p + run / 2 - rail OD / 2 - bar OD / 2;
  * the skirt: sheet inside the lower rails, d = rail OD / 2 + sheet / 2 inside the centre line;
    rolled one piece (R - d) x span long; mitred one flat panel per straight, shortened by
    d tan(turn / 2) at each end that meets another panel (not at a post);
  * the cut file: one closed 4-corner rectangle on CUT for each different piece size, left to right,
    2 in apart, nothing else on CUT; DXF R12 in inches with no audit errors;
  * the fit: clear inside (rolled D - rail OD - 2 sheet; mitred 2 (R cos(turn/2) - rail OD/2 - sheet)),
    bale on end if clear - diameter >= 6, on its side if clear - hypot(diameter, width) >= 6;
  * the design rules: opening top-mid 18 to 30; bar OD at most rail OD - 1/4; first bar end 1 clear of
    the post; clear opening 9 to 14; bale fits; skirt to bale each side at most 21; sleeves 3 long at
    8 and top - 12 (start post), 12 and top - 8 (end post), at least 1 apart;
  * the pin: from 5.5, to = (top - 8) + 1.5 + pin diameter (the handle rests on the top sleeve);
  * the weights: steel 0.2836 lb/in3 (within 0.5 %), sections + pins;
  * the fabrication numbers of the item sheets, from the same rules: the jig frame (datum = the line
    through the two post centres, X from the left post centre, Y square to it toward the outside;
    the ring centre R cos(span / 2) behind it), the rail centre line's offsets (rolled: every 12 in X
    from the left post up to 6 short of the right post, the middle, none within 1.5 of the middle;
    Y = sqrt(R^2 - (X - chord/2)^2) - R cos(span / 2); mitred: the corners), each bar's two centres in
    that frame, both copes of each bar kind (angle and long point at each end), the rail (rolled:
    R +/- rail OD / 2 outside and inside; mitred straights: centre-line length, plus rail OD / 2 x
    tan(turn / 2) at each mitred end for the length over the long points, mitre turn / 2 from square;
    the end coped to the post rail OD / 2 deep), the post (tube = post length - sheet, capped with a
    disc of the rail OD from the skirt sheet), the sleeve centre rail OD / 2 + 1.315 / 2 + 1/16 off the
    post centre, the skirt stitches (1 long at 6 centres from the left end, one at the right end when
    the last is more than 1.5 short of it);
  * the drawing set DXF (when it is in the folder): the figures above are printed on the sheets that
    use them (02 the jig offsets, the bar centres X and the rail heights; 03 the bar centres along the
    rail and the rail sizes; 04 the bar lengths and cope angles, the skirt blank; 05 the post, sleeve
    and pin sizes), read back from the sheets' TEXT entities.

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     # in
WTOL = 0.005    # weights, relative
STEEL = 0.2836  # lb/in3
SL_OD, SL_ID, SL_LEN = 1.315, 1.049, 3.0
manifest = json.loads((HERE / "manifest.json").read_text())
I = manifest["inputs"]
NS, BUILD = int(I["sections"]), I["build"]
R = I["ringDiameterAtRailCL"] / 2
TOP, MID = I["topRailCL"], I["skirtTopCL"]
SPMAX, ANG = I["barSpacingMax"], math.radians(I["barAngle"])
ROD, RWALL = I["railTube"]["od"], I["railTube"]["wall"]
BOD, BWALL = I["barTube"]["od"], I["barTube"]["wall"]
SHEET = I["skirtSheet"]
BALE_D, BALE_W = I["bale"]["diameter"], I["bale"]["width"]

# pin joint
GAP_SL = 1 / 16
C = ROD / 2 + SL_OD / 2 + GAP_SL
DELTA = math.asin(C / R)
SPAN = 2 * math.pi / NS - 2 * DELTA
POSTS_APART = 2 * R * math.sin(SPAN / 2)
if BUILD == "rolled":
    K, TURN, MM = 1, 0.0, 1
    L = R * SPAN
    CORNERS = None
else:
    K0 = max(2, math.ceil(R * SPAN / 30 - 1e-9))
    K = K0
    for kk in range(K0, K0 + 7):
        ch = 2 * R * math.sin(SPAN / (2 * kk))
        mm = max(1, math.ceil(ch / SPMAX - 1e-9))
        if (ch / mm) * math.sin(math.radians(I["barAngle"])) - BOD >= 9 - 1e-9:
            K = kk
            break
    TURN = SPAN / K
    L = K * 2 * R * math.sin(SPAN / (2 * K))
    CORNERS = [(R * math.cos(-SPAN / 2 + i * TURN), R * math.sin(-SPAN / 2 + i * TURN)) for i in range(K + 1)]
STRAIGHT = 2 * R * math.sin(SPAN / (2 * K))
if BUILD != "rolled":
    MM = max(1, math.ceil(STRAIGHT / SPMAX - 1e-9))
POST_LEN = TOP + ROD / 2


def seg_index(s):
    return min(K - 1, max(0, int(s // STRAIGHT + 1e-9)))


def plan_point(s):
    """x, y of the rail centre line at distance s along it from the first post."""
    if BUILD == "rolled":
        a = -SPAN / 2 + s / R
        return R * math.cos(a), R * math.sin(a)
    i = seg_index(s)
    f = (s - i * STRAIGHT) / STRAIGHT
    (x0, y0), (x1, y1) = CORNERS[i], CORNERS[i + 1]
    return x0 + f * (x1 - x0), y0 + f * (y1 - y0)


def tangent(s):
    if BUILD == "rolled":
        a = -SPAN / 2 + s / R
        return -math.sin(a), math.cos(a), 0.0
    i = seg_index(s)
    (x0, y0), (x1, y1) = CORNERS[i], CORNERS[i + 1]
    return (x1 - x0) / STRAIGHT, (y1 - y0) / STRAIGHT, 0.0


def cross(a, b):
    return (a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0])


def dot(a, b):
    return sum(x * y for x, y in zip(a, b))


def long_offset(beta, Rr, r):
    """smallest s(phi) round the bar: the long point's distance back from the rail axis."""
    f = lambda ph: (math.sqrt(Rr * Rr - r * r * math.sin(ph) ** 2) - r * math.cos(ph) * math.cos(beta)) / math.sin(beta)
    n = 3600
    best = min(range(n), key=lambda i: f(2 * math.pi * i / n))
    lo, hi = 2 * math.pi * (best - 1) / n, 2 * math.pi * (best + 1) / n
    g = (math.sqrt(5) - 1) / 2
    for _ in range(80):
        a, b = hi - g * (hi - lo), lo + g * (hi - lo)
        if f(a) < f(b):
            hi = b
        else:
            lo = a
    return f((lo + hi) / 2)


# bars
RUN = (TOP - MID) / math.tan(ANG)
NOPEN = max(2, math.ceil(L / SPMAX - 1e-9)) if BUILD == "rolled" else K * MM
P = L / NOPEN
BARS = []
for j in range(1, NOPEN):
    sb, st = j * P - RUN / 2, j * P + RUN / 2
    (x0, y0), (x1, y1) = plan_point(sb), plan_point(st)
    vec = (x1 - x0, y1 - y0, TOP - MID)
    true = math.sqrt(dot(vec, vec))
    d = tuple(v / true for v in vec)
    tA, tB = tangent(sb), tangent(st)
    bA, bB = math.acos(min(1.0, abs(dot(d, tA)))), math.acos(min(1.0, abs(dot(d, tB))))
    nA, nB = cross(d, tA), cross(d, tB)
    nA = tuple(v / math.sqrt(dot(nA, nA)) for v in nA)
    nB = tuple(v / math.sqrt(dot(nB, nB)) for v in nB)
    turned = math.degrees(math.acos(min(1.0, abs(dot(nA, nB)))))
    lp = true - long_offset(bA, ROD / 2, BOD / 2) - long_offset(bB, ROD / 2, BOD / 2)
    ratio = j * P / STRAIGHT if BUILD != "rolled" else 0.5
    corner = BUILD != "rolled" and abs(ratio - round(ratio)) < 1e-6
    BARS.append((sb, st, true, lp, corner, math.degrees(min(bA, bB)), turned))
TYPES = []
BAR_TYPE = []
for b in BARS:
    for ti, t in enumerate(TYPES):
        if t["corner"] == b[4] and abs(t["lengthCL"] - b[2]) < 5e-4:
            t["qty"] += 1
            BAR_TYPE.append(ti)
            break
    else:
        TYPES.append({"qty": 1, "corner": b[4], "lengthCL": b[2], "lengthLongPoints": b[3], "copeDeg": b[5], "copesTurnedDeg": b[6]})
        BAR_TYPE.append(len(TYPES) - 1)
for ti, t in enumerate(TYPES):
    t["mark"] = "c" if len(TYPES) == 1 else f"c{ti + 1}"
RISE = math.hypot(*plan_point(L / 2)) - R * math.cos(SPAN / 2)
WEDGE = P + RUN / 2 - ROD / 2 - BOD / 2
CLEAR_SQ = P * math.sin(ANG) - BOD
PLACES = NS * NOPEN

# skirt
D_IN = ROD / 2 + SHEET / 2
SK_H = MID - ROD / 2
if BUILD == "rolled":
    PIECES = [(( R - D_IN) * SPAN, 1)]
else:
    short = D_IN * math.tan(TURN / 2)
    ends = STRAIGHT - short
    inner = STRAIGHT - 2 * short
    PIECES = [(ends, 2)] + ([(inner, K - 2)] if K > 2 else [])
SK_AREA = sum(ln * q for ln, q in PIECES) * SK_H

# fit
if BUILD == "rolled":
    CLEAR_IN = 2 * R - ROD - 2 * SHEET
else:
    CLEAR_IN = 2 * (R * math.cos(TURN / 2) - ROD / 2 - SHEET)
ON_END = CLEAR_IN - BALE_D >= 6 - 1e-9
ON_SIDE = CLEAR_IN - math.hypot(BALE_D, BALE_W) >= 6 - 1e-9
GAP = (CLEAR_IN - BALE_D) / 2 if ON_END else (CLEAR_IN - max(BALE_D, BALE_W)) / 2

# sleeves
START_SL = [8, TOP - 12]
END_SL = [12, TOP - 8]

# weights
tube = lambda od, wall: math.pi * (od - wall) * wall
R_AREA, B_AREA = tube(ROD, RWALL), tube(BOD, BWALL)
SL_AREA = tube(SL_OD, (SL_OD - SL_ID) / 2)
W_SECTION = (3 * L * R_AREA + 2 * POST_LEN * R_AREA + sum(b[2] for b in BARS) * B_AREA + SK_AREA * SHEET
             + 4 * SL_LEN * SL_AREA) * STEEL
PIN = manifest["joint"]["pin"]
W_PIN = (PIN["to"] - PIN["from"] + PIN["handle"]) * math.pi * (0.75 / 2) ** 2 * STEEL
W_RING = NS * (W_SECTION + W_PIN)

print(f"verify-round-bale-feeder.py, ezdxf {ezdxf.__version__}, files in {HERE.name}")
bad = 0
count = 0


def check(label, ok, detail=""):
    global bad, count
    count += 1
    bad += 0 if ok else 1
    print(f"{'OK  ' if ok else 'FAIL'} {count:2d} {label}{('  ' + detail) if detail else ''}")


def near(got, want, tol=TOL):
    try:
        return abs(got - want) <= tol
    except TypeError:
        return False


def near_w(got, want):
    try:
        return abs(got - want) <= WTOL * want
    except TypeError:
        return False


S, J, RG = manifest["section"], manifest["joint"], manifest["ring"]
check(f"inputs sensible: {NS} sections, build {BUILD}, ring {2 * R:g} at the rail centre line",
      NS in (3, 4) and BUILD in ("rolled", "mitred") and MID > ROD and TOP > MID and 0 < C / R < 1 and SPAN > 0)
check(f"post centres apart {POSTS_APART:.4f}, span {math.degrees(SPAN):.4f} deg, rail length {L:.4f}",
      near(S["postCentresApart"], POSTS_APART) and near(S["spanDeg"], math.degrees(SPAN)) and near(S["railLengthCL"], L),
      f"manifest {S['postCentresApart']}, {S['spanDeg']}, {S['railLengthCL']}")
check(f"{K} straight(s) per rail, mitre turn {math.degrees(TURN):.4f} deg",
      S["straightsPerRail"] == K and near(S["mitreTurnDeg"], math.degrees(TURN)),
      f"manifest {S['straightsPerRail']}, {S['mitreTurnDeg']}")
check(f"2 posts, length {POST_LEN:.4f}", S["posts"]["qty"] == 2 and near(S["posts"]["length"], POST_LEN), f"manifest {S['posts']}")
B = S["bars"]
check(f"{len(BARS)} bars ({NOPEN} openings) spacing {P:.4f}, clear opening square to the bars {CLEAR_SQ:.4f}",
      B["qty"] == len(BARS) and near(B["spacing"], P) and near(B["clearSquare"], CLEAR_SQ),
      f"manifest {B['qty']}, {B['spacing']}, {B['clearSquare']}")
mt = B.get("types", [])
types_ok = len(mt) == len(TYPES)
if types_ok:
    for m, t in zip(mt, TYPES):
        types_ok = (types_ok and m.get("mark") == t["mark"] and m.get("qty") == t["qty"] and m.get("corner") == t["corner"]
                    and near(m.get("lengthCL"), t["lengthCL"]) and near(m.get("lengthLongPoints"), t["lengthLongPoints"])
                    and near(m.get("copeDeg"), t["copeDeg"], 0.02) and near(m.get("copesTurnedDeg"), t["copesTurnedDeg"], 0.02))
check(f"{len(TYPES)} bar type(s): " + "; ".join(
    f"{t['mark']} {t['qty']} x {t['lengthCL']:.4f} / {t['lengthLongPoints']:.4f} long points, cope {t['copeDeg']:.2f}, turned {t['copesTurnedDeg']:.2f}"
    for t in TYPES), types_ok, "manifest " + json.dumps(mt))
ends_ok = len(B["ends"]) == len(BARS) and all(
    near(e.get("midRail"), b[0]) and near(e.get("topRail"), b[1]) and e.get("type") == ti
    for e, b, ti in zip(B["ends"], BARS, BAR_TYPE))
check("every bar's type and end on the mid rail and on the top rail, along the rail centre line", ends_ok,
      " ".join(f"{b[0]:.3f}/{b[1]:.3f}" for b in BARS))
check(f"rise {RISE:.4f}, wedge at the post clear {WEDGE:.4f}", near(S.get("rise"), RISE) and near(S.get("wedgeAtPostClear"), WEDGE),
      f"manifest {S.get('rise')}, {S.get('wedgeAtPostClear')}")
check(f"all bars end on the rails, between the posts (0 to {L:.3f})", all(b[0] > 0 and b[1] < L for b in BARS))
check(f"{PLACES} feeding places, {NOPEN} openings per section",
      RG["feedingPlaces"] == PLACES and RG["openingsPerSection"] == NOPEN, f"manifest {RG['feedingPlaces']}, {RG['openingsPerSection']}")
check(f"clear inside {CLEAR_IN:.4f}, bale on end {ON_END}, on its side {ON_SIDE}",
      near(RG["clearInside"], CLEAR_IN) and RG["baleOnEnd"] == ON_END and RG["baleOnSide"] == ON_SIDE,
      f"manifest {RG['clearInside']}, {RG['baleOnEnd']}, {RG['baleOnSide']}")

# skirt pieces and DXF
SK = S["skirt"]
mp = SK["pieces"]
want_pieces = sorted(PIECES, reverse=True)
pieces_ok = near(SK["height"], SK_H) and len(mp) == len(want_pieces)
if pieces_ok:
    for m, (ln, q), i in zip(mp, want_pieces, range(len(mp))):
        x0 = sum(w[0] + 2 for w in want_pieces[:i])
        pieces_ok = pieces_ok and near(m["length"], ln) and near(m["height"], SK_H) and m["qtyPerSection"] == q and near(m["fromLeft"], x0)
check("skirt: " + ", ".join(f"{q} x {ln:.4f} x {SK_H:.4f}" for ln, q in want_pieces) + " per section", pieces_ok,
      "manifest " + ", ".join(f"{m['qtyPerSection']} x {m['length']}" for m in mp))
if BUILD == "rolled":
    check(f"skirt rolled outside radius {R - D_IN + SHEET / 2:.4f}", near(((SK.get("rolled") or {}).get("outsideR")), R - D_IN + SHEET / 2))
else:
    check("skirt flat panels, not rolled", SK.get("rolled") is None)

doc = ezdxf.readfile(HERE / SK["file"])
msp = doc.modelspace()
check("DXF R12 in inches", doc.dxfversion == "AC1009" and doc.header.get("$INSUNITS", 1) == 1,
      f"{doc.dxfversion}, $INSUNITS {doc.header.get('$INSUNITS')}")
auditor = doc.audit()
check("no audit errors", not auditor.has_errors, f"{len(auditor.errors)} errors")
cut = [e for e in msp if e.dxf.layer == "CUT"]
rects, rect_ok = [], True
for e in cut:
    if e.dxftype() == "POLYLINE":
        pts = [(v.dxf.location[0], v.dxf.location[1]) for v in e.vertices]
        closed = e.is_closed
    elif e.dxftype() == "LWPOLYLINE":
        pts = [(x, y) for x, y, *_ in e.get_points()]
        closed = e.closed
    else:
        rect_ok = False
        continue
    xs, ys = sorted({round(x, 4) for x, _ in pts}), sorted({round(y, 4) for _, y in pts})
    axis = len(pts) == 4 and len(xs) == 2 and len(ys) == 2 and all(
        (a[0] == b[0]) != (a[1] == b[1]) for a, b in zip(pts, pts[1:] + pts[:1]))
    if not (closed and axis):
        rect_ok = False
        continue
    rects.append((min(x for x, _ in pts), max(x for x, _ in pts) - min(x for x, _ in pts),
                  max(y for _, y in pts) - min(y for _, y in pts)))
rects.sort()
check(f"CUT holds only {len(want_pieces)} closed 4-corner rectangle(s)", rect_ok and len(cut) == len(want_pieces) == len(rects),
      f"{len(cut)} entities on CUT")
dxf_ok = len(rects) == len(want_pieces)
if dxf_ok:
    x = 0.0
    for r, (ln, q) in zip(rects, want_pieces):
        dxf_ok = dxf_ok and near(r[1], ln) and near(r[2], SK_H) and near(r[0], x)
        x += ln + 2
check("rectangle sizes " + ", ".join(f"{ln:.4f} x {SK_H:.4f}" for ln, q in want_pieces) + ", left to right 2 in apart", dxf_ok,
      " ".join(f"{w:.4f}x{h:.4f}@{x0:.3f}" for x0, w, h in rects))

# sleeves
sl = J["sleeve"]
check(f"sleeves 1 in Sch 40 (OD {SL_OD}, ID {SL_ID}), 3 long, 1/16 off each post, start post at {START_SL[0]} and {START_SL[1]:g}, end post at {END_SL[0]} and {END_SL[1]:g}",
      near(sl["od"], SL_OD) and near(sl["id"], SL_ID) and near(sl["length"], SL_LEN) and near(sl.get("gapToPost"), GAP_SL)
      and len(sl["startPostCentres"]) == 2 and len(sl["endPostCentres"]) == 2
      and all(near(a, b) for a, b in zip(sl["startPostCentres"], START_SL))
      and all(near(a, b) for a, b in zip(sl["endPostCentres"], END_SL)),
      f"manifest {sl['startPostCentres']}, {sl['endPostCentres']}")
check("sleeves at least 1 apart on each post and inside the post",
      all(b - a - SL_LEN >= 1 - 1e-9 for pair in (START_SL, END_SL) for a, b in [pair]) and START_SL[0] - SL_LEN / 2 >= 0
      and END_SL[1] + SL_LEN / 2 <= POST_LEN)
PIN_TO = END_SL[1] + SL_LEN / 2 + PIN["d"]
check(f"pin 0.75 dia from 5.5 to {PIN_TO:g} (handle rests on the top sleeve), 3 in handle",
      near(PIN["from"], START_SL[0] - SL_LEN / 2 - 1) and near(PIN["to"], PIN_TO) and near(PIN["handle"], 3) and near(PIN["d"], 0.75),
      f"pin {PIN['from']} to {PIN['to']}")

# design rules
rules = {
    "neck": (18 <= TOP - MID <= 30, f"opening top-mid {TOP - MID:g}"),
    "bar": (BOD <= ROD - 0.25 + 1e-9, f"bar OD {BOD} rail OD {ROD}"),
    "post": (P - RUN / 2 - ROD / 2 - BOD / 2 >= 1 - 1e-9, f"first bar end {P - RUN / 2 - ROD / 2 - BOD / 2:.3f} clear of the post"),
    "clear": (9 <= CLEAR_SQ <= 14, f"clear opening {CLEAR_SQ:.4f}"),
    "bale": (ON_END or ON_SIDE, f"bale on end {ON_END}, on side {ON_SIDE}"),
    "reach": (GAP <= 21 + 1e-9, f"skirt to bale {GAP:.4f}"),
    "sleeves": (all(b - a - SL_LEN >= 1 - 1e-9 for a, b in (START_SL, END_SL)), "sleeves stack"),
}
for key, (ok, text) in rules.items():
    check(f"design rule {key}: {text}", ok)
mc = {c["id"]: c["ok"] for c in manifest["checks"]}
check("manifest's own design checks agree with these", all(mc.get(k) == v[0] for k, v in rules.items()) and set(mc) == set(rules),
      f"manifest {mc}")

# weights
check(f"section weight {W_SECTION:.4f} lb within 0.5 %", near_w(S["weight"], W_SECTION), f"manifest {S['weight']}")
check(f"pin weight {W_PIN:.4f} lb within 0.5 %", near_w(RG["pinWeight"], W_PIN), f"manifest {RG['pinWeight']}")
check(f"ring weight {W_RING:.4f} lb within 0.5 %", near_w(RG["weight"], W_RING), f"manifest {RG['weight']}")
# fabrication numbers (sheets 02-05)
BEHIND = R * math.cos(SPAN / 2)


def jig(sv):
    x, y = plan_point(sv)
    return y + R * math.sin(SPAN / 2), x - BEHIND


if BUILD == "rolled":
    xm = POSTS_APART / 2
    xs, xv = [], 12.0
    while xv < POSTS_APART - 6 + 1e-9:
        xs.append(xv)
        xv += 12
    xs = sorted([v for v in xs if abs(v - xm) > 1.5] + [xm])
    STATIONS = [(v, math.sqrt(R * R - (v - xm) ** 2) - BEHIND) for v in xs]
else:
    STATIONS = [jig(i * STRAIGHT) for i in range(1, K)]
JG = S.get("jig", {})
mst = JG.get("stations", [])
check(f"jig: ring centre {BEHIND:.4f} behind datum A, {len(STATIONS)} rail line offsets "
      + ", ".join(f"{x:.3f}/{y:.3f}" for x, y in STATIONS),
      near(JG.get("ringCentreBehindDatum"), BEHIND) and len(mst) == len(STATIONS)
      and all(near(m.get("x"), x) and near(m.get("y"), y) for m, (x, y) in zip(mst, STATIONS)), "manifest " + json.dumps(mst))
JIG_BARS = [(jig(b[0]), jig(b[1])) for b in BARS]
check("every bar's centres on the mid and top rails in the jig frame (X, Y from the left post centre)",
      len(B["ends"]) == len(BARS) and all(
          all(near(e.get("jigMid", [None, None])[k], jm[k]) and near(e.get("jigTop", [None, None])[k], jt[k]) for k in (0, 1))
          for e, (jm, jt) in zip(B["ends"], JIG_BARS)),
      " ".join(f"{jm[0]:.3f}/{jt[0]:.3f}" for jm, jt in JIG_BARS))
COPES = []
for ti, t in enumerate(TYPES):
    j = BAR_TYPE.index(ti)
    sb, st = BARS[j][0], BARS[j][1]
    (x0, y0), (x1, y1) = plan_point(sb), plan_point(st)
    vec = (x1 - x0, y1 - y0, TOP - MID)
    d = tuple(v / math.sqrt(dot(vec, vec)) for v in vec)
    bA, bB = math.acos(min(1.0, abs(dot(d, tangent(sb))))), math.acos(min(1.0, abs(dot(d, tangent(st)))))
    COPES.append((math.degrees(bA), math.degrees(bB), long_offset(bA, ROD / 2, BOD / 2), long_offset(bB, ROD / 2, BOD / 2)))
check("both copes of each bar kind: " + "; ".join(f"{t['mark']} {a:.2f}/{b:.2f} deg, long points {la:.4f}/{lb:.4f}" for t, (a, b, la, lb) in zip(TYPES, COPES)),
      len(mt) == len(TYPES) and all(near(m.get("copeEnd1Deg"), a, 0.02) and near(m.get("copeEnd2Deg"), b, 0.02)
                                    and near(m.get("longPointEnd1"), la) and near(m.get("longPointEnd2"), lb) for m, (a, b, la, lb) in zip(mt, COPES)))
RL = S.get("rail", {})
if BUILD == "rolled":
    STR = []
    rail_ok = (near((RL.get("rolled") or {}).get("rCL"), R) and near((RL.get("rolled") or {}).get("rOutside"), R + ROD / 2)
               and near((RL.get("rolled") or {}).get("rInside"), R - ROD / 2) and RL.get("straights") == [])
else:
    hx = (ROD / 2) * math.tan(TURN / 2)
    STR = [("a1", 6, STRAIGHT, STRAIGHT + hx)] + ([("a2", 3 * (K - 2), STRAIGHT, STRAIGHT + 2 * hx)] if K > 2 else [])
    ms = RL.get("straights", [])
    rail_ok = (RL.get("rolled") is None and near(RL.get("mitreFromSquareDeg"), math.degrees(TURN / 2)) and len(ms) == len(STR)
               and all(m.get("mark") == a and m.get("qty") == q and near(m.get("lengthCL"), lc) and near(m.get("lengthLongPoints"), lp)
                       for m, (a, q, lc, lp) in zip(ms, STR)))
check(f"rail: cut {L:.4f} at CL, chord {POSTS_APART:.4f}, rise {RISE:.4f}, coped to the post {ROD / 2:.4f} deep"
      + ("" if BUILD == "rolled" else ", straights " + ", ".join(f"{a} {q} x {lc:.4f} / {lp:.4f}" for a, q, lc, lp in STR)),
      rail_ok and near(RL.get("cutAtCL"), L) and near(RL.get("chord"), POSTS_APART) and near(RL.get("rise"), RISE)
      and near((RL.get("copeToPost") or {}).get("depth"), ROD / 2), "manifest " + json.dumps(RL)[:200])
PT = S["posts"]
POST_TUBE = POST_LEN - SHEET
check(f"post tube {POST_TUBE:.4f} under a {ROD} x {SHEET} cap, rails at {ROD / 2:g}, {MID:g}, {TOP:g}; sleeve centre {C:.4f} off the post centre",
      near(PT.get("tubeCut"), POST_TUBE) and near((PT.get("cap") or {}).get("d"), ROD) and near((PT.get("cap") or {}).get("t"), SHEET)
      and len(PT.get("railCentres", [])) == 3 and all(near(a, b) for a, b in zip(PT.get("railCentres", []), [ROD / 2, MID, TOP]))
      and near(sl.get("centreFromPostCL"), C), f"manifest {PT}")


def stitches(ln):
    out, cv = [], 0.5
    while cv <= ln - 0.5 + 1e-9:
        out.append(cv)
        cv += 6
    if ln - 0.5 - out[-1] > 1.5:
        out.append(ln - 0.5)
    return out


st_ok = len(mp) == len(want_pieces) and all(
    len(m.get("stitchCentres", [])) == len(stitches(ln)) and all(near(a, b) for a, b in zip(m.get("stitchCentres", []), stitches(ln)))
    for m, (ln, q) in zip(mp, want_pieces))
check("skirt stitches: " + ", ".join(f"{len(stitches(ln))} on each long edge of the {ln:.3f}" for ln, q in want_pieces), st_ok)

# the figures printed on the sheets (drawing set DXF)
DS = manifest.get("drawingSet") or {}
check("5 sheets in the set", len(DS.get("sheets", [])) == 5, f"manifest {DS.get('sheets')}")
set_file = HERE / DS.get("file", "")
if DS.get("file") and set_file.exists():
    sd = ezdxf.readfile(set_file)
    per = {}
    for e in sd.modelspace():
        if e.dxftype() != "TEXT":
            continue
        k = int(e.dxf.insert[0] // (431.8 + 40))
        per.setdefault(k, []).extend(float(v) for v in re.findall(r"\d+\.\d+", e.dxf.text))

    def printed(sheet, vals, dec=3):
        have = per.get(sheet - 1, [])
        tol = 0.5 * 10 ** -dec + 1e-6
        missing = [v for v in vals if not any(abs(h - v) <= tol for h in have)]
        return not missing, missing

    want2 = [POSTS_APART, MID, TOP, POST_LEN] + [y for _, y in STATIONS] + [jm[0] for jm, _ in JIG_BARS] + [jt[0] for _, jt in JIG_BARS]
    ok2, miss2 = printed(2, want2)
    check(f"sheet 02 prints the post centres, rail heights, {len(STATIONS)} jig offsets and {2 * len(BARS)} bar centres X", ok2, f"missing {miss2[:6]}")
    want3 = [b[0] for b in BARS] + [b[1] for b in BARS] + ([L, R, POSTS_APART, RISE] if BUILD == "rolled" else [v for _, _, lc, lp in STR for v in (lc, lp)])
    ok3, miss3 = printed(3, want3)
    check(f"sheet 03 prints the {2 * len(BARS)} bar centres along the rail and the rail sizes", ok3, f"missing {miss3[:6]}")
    want4 = [v for t in TYPES for v in (t["lengthLongPoints"], t["lengthCL"])] + [ln for ln, _ in want_pieces] + [SK_H]
    ok4a, miss4a = printed(4, want4)
    ok4b, miss4b = printed(4, [v for a, b, _, _ in COPES for v in (a, b)] + [t["copesTurnedDeg"] for t in TYPES if t["copesTurnedDeg"] >= 0.05], 1)
    check("sheet 04 prints each bar kind's lengths and cope angles and the skirt blank", ok4a and ok4b, f"missing {miss4a[:4]} {miss4b[:4]}")
    want5 = [POST_TUBE, POST_LEN, C, SL_LEN, SL_OD, SL_ID] + START_SL + END_SL + [PIN_TO - PIN["from"]]
    ok5, miss5 = printed(5, want5)
    check("sheet 05 prints the post, sleeve and pin sizes", ok5, f"missing {miss5[:6]}")
else:
    print("     (no drawing set DXF here: the printed figures are not checked)")
print("ALL CHECKS PASSED" if not bad else f"{bad} CHECK(S) FAILED")
sys.exit(1 if bad else 0)
