#!/usr/bin/env python3
"""
Parametric generator for the LED candlestick: STLs, preview PNGs and the SVG drawings,
all from the one parameter block below (mm).

Printed parts (exported in print orientation):
  bowl      -- lower half of the base: floor, wall, three screw columns, board rails that
               double as the battery shelf, USB-C window. Print as modelled (floor down).
  cap       -- upper half: shallow cone, flare, neck with the tube socket, finger ring.
               Solid, flat underside on the bed, three heat-set-insert holes.
  diffuser  -- the "flame": closed tube with a spigot that carries the brass touch collar.
               Print CLOSED END DOWN in white or natural filament.
  coupler   -- insulating spacer between the collar and the stem tube. Print flange down.
Bought parts the cavities are sized for (measure yours):
  * 3/8 in OD x 0.014 in wall round brass tube (K&S), one 12 in length
  * DFRobot FireBeetle 2 ESP32-E, 60 x 25.4, USB-C on a short end
  * LiPo pouch ~7 x 50 x 60 ("705060"), PH2.0 lead, protected
  * 3 V single-ended LED filament, 25 mm
Hardware: 3x M3 heat-set insert (4.0 mm hole, <= 5 mm long), 3x M3x25 socket-head screws.

Requirements:  pip install manifold3d trimesh numpy matplotlib
Usage:         python3 generate_candlestick.py
"""
import math
import os
import numpy as np
from manifold3d import Manifold, CrossSection

HERE = os.path.dirname(os.path.abspath(__file__))
PREVIEW_DIR = os.path.join(HERE, "previews")
os.makedirs(PREVIEW_DIR, exist_ok=True)
SEG = 128

# -- overall (stated: 26 cm tall; the rest is est. from the product photos) ------------
TOTAL_H = 260.0
BASE_D = 104.0             # rim diameter (est.: the listing's "12 cm" doesn't match its photos)
Z_SEAM = 22.0              # bowl/cap joint = the rim, the widest point
Z_LAND = 25.0              # top of the 3 mm vertical land above the seam
CONE_DEG = 15.0            # slope of the cap's top surface
FLARE_R = 20.0             # fillet between the cone and the neck
NECK_D = 14.0
Z_NECK = 55.0              # top of the neck, where the tube enters
BOWL_START_DEG = 45.0      # wall angle at the floor (from horizontal); >= 45 prints unsupported

# -- stem ---------------------------------------------------------------------------------
TUBE_OD = 9.525            # 3/8 in
TUBE_ID = 8.81             # 0.014 in wall
TUBE_SOCKET_CLR = 0.2      # on diameter
Z_TUBE_SEAT = 29.0         # bottom of the tube socket
WIRE_HOLE_D = 6.0
COLLAR_L = 12.0            # brass touch collar, cut from the same tube
GAP_L = 1.0                # coupler flange = the insulating line under the collar
DIFF_L = 40.0              # exposed diffuser
DIFF_WALL = 1.2
SPIGOT_CLR = 0.12          # on diameter, printed spigots into the brass tube
COUPLER_SPIGOT_L = 10.0
NOSE_D, NOSE_L = 6.0, 6.0  # diffuser nose that plugs into the coupler
BORE_D = 4.0               # wire bore through the diffuser spigot
SLOT_W = 2.0               # slot for the touch wire, through the spigot wall

# -- base internals -----------------------------------------------------------------------
WALL = 3.0                 # measured horizontally (2.1 normal thickness at the floor)
FLOOR_T = 2.4
LIP_T, LIP_H, LIP_CLR = 1.4, 1.5, 0.25
COL_D = 8.0
COLS = [(33.0, 0.0), (0.0, 33.0), (0.0, -33.0)]
M3_CLEAR, M3_HEAD_D, M3_HEAD_H = 3.4, 6.2, 3.5
SCREW_L = 25.0
INSERT_D, INSERT_DEPTH = 4.0, 5.5
BOARD_L, BOARD_W = 60.0, 25.4          # FireBeetle 2 ESP32-E (stated)
BOARD_CLR = 0.4
BOARD_USB_X = -40.5                    # x of the board's USB end
TAPE_T, PCB_T, BOARD_STACK = 1.0, 1.6, 4.5   # foam tape, PCB, tallest part above the PCB (est.)
USB_W, USB_H = 13.0, 7.5               # window for the plug's overmold
RAIL_T = 2.0
RAIL_X = (-28.0, 18.0)
Z_SHELF = 11.5                         # rail tops = underside of the battery
BATT = (60.0, 50.0, 7.0)               # L (x), W (y), T
BATT_X0 = -38.0
RING_OD, RING_ID, RING_W = 20.0, 14.0, 7.0
RING_R = 40.0                          # ring centre, from the lamp axis
RING_SINK = 3.0                        # how far the ring is sunk into the cone

# -- derived --------------------------------------------------------------------------------
R_RIM = BASE_D / 2
R_NECK = NECK_D / 2
R_ARC = Z_SEAM / math.sin(math.radians(90 - BOWL_START_DEG))    # bowl wall arc: 45 deg -> vertical
R_BOT = R_RIM - R_ARC * (1 - math.cos(math.radians(90 - BOWL_START_DEG)))
TAN = math.tan(math.radians(CONE_DEG))
FLARE_RC = R_NECK + FLARE_R
FLARE_ZC = Z_LAND + (R_RIM - FLARE_RC) * TAN + FLARE_R / math.cos(math.radians(CONE_DEG))
Z_DIFF = TOTAL_H - DIFF_L              # diffuser shoulder
Z_COLLAR = Z_DIFF - COLLAR_L
Z_TUBE_TOP = Z_COLLAR - GAP_L
TUBE_L = Z_TUBE_TOP - Z_TUBE_SEAT
SPIGOT_D = TUBE_ID - SPIGOT_CLR
BOARD_Z0 = FLOOR_T + TAPE_T
USB_Z = BOARD_Z0 + PCB_T + 1.6         # connector centre
RING_Z = Z_LAND + (R_RIM - RING_R) * TAN + RING_OD / 2 - RING_SINK


def bowl_r(z):
    """Outside radius of the bowl at height z (0..Z_SEAM)."""
    return R_RIM - R_ARC + math.sqrt(R_ARC ** 2 - (Z_SEAM - z) ** 2)


def cone_z(r):
    return Z_LAND + (R_RIM - r) * TAN


def cap_profile(n=24):
    """(r, z) points of the cap's outside, from the rim up to the neck top."""
    pts = [(R_RIM, Z_SEAM), (R_RIM, Z_LAND)]
    t0 = math.radians(90 - CONE_DEG)
    for i in range(n + 1):
        t = t0 * (1 - i / n)
        pts.append((FLARE_RC - FLARE_R * math.cos(t), FLARE_ZC - FLARE_R * math.sin(t)))
    pts += [(R_NECK, Z_NECK - 2.0), (R_NECK - 1.4, Z_NECK)]
    return pts


def bowl_profile(n=24):
    return [(bowl_r(Z_SEAM * i / n), Z_SEAM * i / n) for i in range(n + 1)]


def revolve(pts):
    return Manifold.revolve(CrossSection([np.array(pts, float)]), SEG)

def box(x0, x1, y0, y1, z0, z1):
    return Manifold.cube((x1 - x0, y1 - y0, z1 - z0)).translate((x0, y0, z0))

def cyl(x, y, z0, z1, d):
    return Manifold.cylinder(z1 - z0, d / 2, d / 2, SEG).translate((x, y, z0))


# ---------------------------------------------------------------------------------------------

def part_bowl():
    outer = bowl_profile()
    lip = [(R_RIM - WALL + LIP_T, Z_SEAM), (R_RIM - WALL + LIP_T, Z_SEAM + LIP_H), (0, Z_SEAM + LIP_H)]
    body = revolve([(0, 0)] + outer + lip)
    inner = [(max(r - WALL, 0.1), z) for r, z in outer if z >= FLOOR_T - 1e-6]
    inner[0] = (bowl_r(FLOOR_T) - WALL, FLOOR_T)
    cavity = revolve([(0, FLOOR_T)] + inner + [(R_RIM - WALL, Z_SEAM + LIP_H + 1), (0, Z_SEAM + LIP_H + 1)])
    body -= cavity
    for x, y in COLS:
        body += cyl(x, y, FLOOR_T - 0.1, Z_SEAM, COL_D)
    half = BOARD_W / 2 + BOARD_CLR
    for s in (1, -1):                                   # board rails / battery shelf
        y0, y1 = sorted((s * half, s * (half + RAIL_T)))
        body += box(RAIL_X[0], RAIL_X[1], y0, y1, FLOOR_T - 0.1, Z_SHELF)
    ex = BOARD_USB_X + BOARD_L + BOARD_CLR              # end stop: takes the push of the USB plug
    body += box(ex, ex + 2.0, -6, 6, FLOOR_T - 0.1, FLOOR_T + 4.0)
    for x, y in COLS:
        body -= cyl(x, y, -1, Z_SEAM + 1, M3_CLEAR)
        body -= cyl(x, y, -1, M3_HEAD_H, M3_HEAD_D)
    body -= box(-R_RIM - 5, BOARD_USB_X, -USB_W / 2, USB_W / 2, USB_Z - USB_H / 2, USB_Z + USB_H / 2)
    return body


def part_cap():
    body = revolve([(0, Z_SEAM)] + cap_profile() + [(0, Z_NECK)])
    ring = Manifold.cylinder(RING_W, RING_OD / 2, RING_OD / 2, SEG) - \
        Manifold.cylinder(RING_W + 2, RING_ID / 2, RING_ID / 2, SEG).translate((0, 0, -1))
    ring = ring.translate((0, 0, -RING_W / 2)).rotate((90, 0, 0)).translate((RING_R, 0, RING_Z))
    body += ring
    body -= cyl(0, 0, Z_TUBE_SEAT, Z_NECK + 1, TUBE_OD + TUBE_SOCKET_CLR)
    body -= cyl(0, 0, Z_SEAM - 1, Z_TUBE_SEAT + 0.1, WIRE_HOLE_D)
    r0 = R_RIM - WALL - LIP_CLR                         # groove for the bowl's lip
    r1 = R_RIM - WALL + LIP_T + LIP_CLR
    body -= revolve([(r0, Z_SEAM - 1), (r1, Z_SEAM - 1), (r1, Z_SEAM + LIP_H + 0.3), (r0, Z_SEAM + LIP_H + 0.3)])
    for x, y in COLS:
        body -= cyl(x, y, Z_SEAM - 1, Z_SEAM + INSERT_DEPTH, INSERT_D)
    return body


def part_diffuser():
    """Modelled with the shoulder at z = 0 and the closed end up; exported flipped."""
    ro, ri, L = TUBE_OD / 2, TUBE_OD / 2 - DIFF_WALL, DIFF_L
    rb, rs, rn = BORE_D / 2, SPIGOT_D / 2, NOSE_D / 2
    zb = -(COLLAR_L + NOSE_L)
    pts = [(rb, zb), (rn, zb), (rn, -COLLAR_L), (rs, -COLLAR_L), (rs, 0), (ro, 0)]
    for i in range(9):                                  # rounded top edge, r = 1.5
        t = math.radians(90 * i / 8)
        pts.append((ro - 1.5 + 1.5 * math.cos(t), L - 1.5 + 1.5 * math.sin(t)))
    z1 = 1.5 + (ri - rb)                                # 45 deg cone from the bore out to the cavity
    pts += [(0, L), (0, L - DIFF_WALL), (ri, L - DIFF_WALL), (ri, z1), (rb, 1.5)]
    body = revolve(pts)
    body -= box(0, ro + 1, -SLOT_W / 2, SLOT_W / 2, -COLLAR_L - 0.1, -3.0)
    return body


def part_coupler():
    """Flange (the visible 1 mm line) on top of a spigot that plugs into the stem tube. z = 0 at the tube top."""
    body = revolve([(NOSE_D / 2 + 0.1, -COUPLER_SPIGOT_L), (SPIGOT_D / 2, -COUPLER_SPIGOT_L), (SPIGOT_D / 2, 0),
                    (TUBE_OD / 2, 0), (TUBE_OD / 2, GAP_L), (NOSE_D / 2 + 0.1, GAP_L)])
    return body


def flipped(man):
    return man.rotate((180, 0, 0))


def dummies():
    board = box(BOARD_USB_X, BOARD_USB_X + BOARD_L, -BOARD_W / 2, BOARD_W / 2, BOARD_Z0, BOARD_Z0 + PCB_T + BOARD_STACK)
    batt = box(BATT_X0, BATT_X0 + BATT[0], -BATT[1] / 2, BATT[1] / 2, Z_SHELF, Z_SHELF + BATT[2])
    tube = cyl(0, 0, Z_TUBE_SEAT, Z_TUBE_TOP, TUBE_OD) - cyl(0, 0, Z_TUBE_SEAT - 1, Z_TUBE_TOP + 1, TUBE_ID)
    collar = cyl(0, 0, Z_COLLAR, Z_DIFF, TUBE_OD) - cyl(0, 0, Z_COLLAR - 1, Z_DIFF + 1, TUBE_ID)
    return {"board": board, "battery": batt, "tube": tube, "collar": collar}


def fit_check():
    problems = []
    bowl, cap = part_bowl(), part_cap()
    diff = part_diffuser().translate((0, 0, Z_DIFF))
    coup = part_coupler().translate((0, 0, Z_TUBE_TOP))
    d = dummies()
    pairs = [("bowl", bowl, "cap", cap), ("diffuser", diff, "coupler", coup)]
    for n in d:
        for pn, p in (("bowl", bowl), ("cap", cap), ("diffuser", diff), ("coupler", coup)):
            pairs.append((n, d[n], pn, p))
    pairs.append(("board", d["board"], "battery", d["battery"]))
    for an, a, bn, b in pairs:
        v = (a ^ b).volume()
        if v > 0.5:
            problems.append(f"{an} intersects {bn} ({v:.1f} mm3)")
    if Z_SHELF + BATT[2] > Z_SEAM - 2.0:
        problems.append("less than 2 mm above the battery for wires")
    if Z_SHELF < BOARD_Z0 + PCB_T + BOARD_STACK:
        problems.append("battery shelf is lower than the tallest part on the board")
    for x, y in COLS:
        left = cone_z(math.hypot(x, y)) - (Z_SEAM + INSERT_DEPTH)
        if left < 2.0:
            problems.append(f"only {left:.1f} mm of cap above the insert at ({x:.0f},{y:.0f})")
    reach = M3_HEAD_H + SCREW_L - Z_SEAM
    if not 3.0 <= reach <= INSERT_DEPTH + 1.5:
        problems.append(f"M3x{SCREW_L:.0f} reaches {reach:.1f} mm into the cap")
    if (R_NECK - 1.4) - (TUBE_OD + TUBE_SOCKET_CLR) / 2 < 0.6:
        problems.append("neck wall around the tube is under 0.6 mm at the top")
    if DIFF_L - DIFF_WALL - 4 < 28:
        problems.append("diffuser cavity is short for a 25 mm filament")
    return problems


PARTS = {
    "bowl": (part_bowl, (0.72, 0.58, 0.30)),
    "cap": (part_cap, (0.72, 0.58, 0.30)),
    "diffuser": (lambda: flipped(part_diffuser()), (0.92, 0.90, 0.84)),
    "coupler": (lambda: flipped(part_coupler()), (0.25, 0.25, 0.27)),
}


def to_trimesh(man):
    import trimesh
    mesh = man.to_mesh()
    return trimesh.Trimesh(vertices=np.asarray(mesh.vert_properties, dtype=np.float64)[:, :3],
                           faces=np.asarray(mesh.tri_verts, dtype=np.int64), process=True)


def render_preview(parts, name, elev=22, azim=-60, size=(7, 6)):
    import matplotlib
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt
    from mpl_toolkits.mplot3d.art3d import Poly3DCollection
    fig = plt.figure(figsize=size)
    ax = fig.add_subplot(projection="3d")
    light = np.array([0.4, -0.6, 0.7]); light /= np.linalg.norm(light)
    lo_all, hi_all = [], []
    for tm, rgb in parts:
        pc = Poly3DCollection(tm.vertices[tm.faces], edgecolor="none")
        lum = np.clip(tm.face_normals @ light, 0, 1) * 0.7 + 0.3
        pc.set_facecolor(np.column_stack([lum * rgb[0], lum * rgb[1], lum * rgb[2], np.ones_like(lum)]))
        ax.add_collection3d(pc)
        lo_all.append(tm.bounds[0]); hi_all.append(tm.bounds[1])
    lo, hi = np.min(lo_all, axis=0), np.max(hi_all, axis=0)
    ax.set_xlim(lo[0], hi[0]); ax.set_ylim(lo[1], hi[1]); ax.set_zlim(lo[2], hi[2])
    ax.set_box_aspect(tuple(hi - lo), zoom=1.0)
    ax.set_axis_off(); ax.view_init(elev=elev, azim=azim)
    fig.tight_layout(pad=0)
    fig.savefig(os.path.join(PREVIEW_DIR, f"{name}.png"), dpi=110, bbox_inches="tight", facecolor="white")
    plt.close(fig)


# ---------------------------------------------------------------------------------------------
# SVG drawings (white background so they read in dark mode)

STYLE = """<style>
  .bg{fill:#fff}
  .pr{fill:#d9d2c3;stroke:#3a342a;stroke-width:1.3;stroke-linejoin:round}
  .cut{fill:#c9bfa8;stroke:#3a342a;stroke-width:1.3;stroke-linejoin:round}
  .br{fill:#e3c36a;stroke:#6a5210;stroke-width:1.2;stroke-linejoin:round}
  .df{fill:#fbf3d6;stroke:#8a7a4a;stroke-width:1.2;stroke-linejoin:round}
  .blk{fill:#55555c;stroke:#222;stroke-width:1}
  .pcb{fill:#9cc3a0;stroke:#2f5d36;stroke-width:1.1}
  .bat{fill:#f0cf8a;stroke:#8a6412;stroke-width:1.1}
  .led{fill:#ffb347;stroke:#b36a00;stroke-width:1}
  .void{fill:#fff;stroke:#3a342a;stroke-width:1.1}
  .nos{fill:#fff;stroke:none}
  .hid{fill:none;stroke:#7a6a5a;stroke-width:1.1;stroke-dasharray:5 3}
  .cl{fill:none;stroke:#999;stroke-width:.8;stroke-dasharray:14 4 3 4}
  .wire{fill:none;stroke:#b0452b;stroke-width:1.4}
  .w2{fill:none;stroke:#333;stroke-width:1.5}
  .dim{stroke:#1f5fa8;stroke-width:1;fill:none}
  .ext{stroke:#8fb0d8;stroke-width:.8}
  .t{font:12px 'Helvetica Neue',Arial,sans-serif;fill:#1f3a5f}
  .n{font:11px 'Helvetica Neue',Arial,sans-serif;fill:#444}
  .h{font:600 15px 'Helvetica Neue',Arial,sans-serif;fill:#222}
</style>
<defs><marker id="a" viewBox="0 0 8 8" refX="8" refY="4" markerWidth="7" markerHeight="7" orient="auto-start-reverse">
<path d="M0,0 L8,4 L0,8 z" fill="#1f5fa8"/></marker></defs>"""


def mm(v):
    s = f"{v:.1f}".rstrip("0").rstrip(".")
    return s


class Svg:
    """x right, z up (or y up for plans); k px per mm; (ox, oy) is the pixel position of (0, 0)."""

    def __init__(self, w, h, ox, oy, k):
        self.w, self.h, self.ox, self.oy, self.k, self.p = w, h, ox, oy, k, []

    def X(self, v): return self.ox + v * self.k
    def Y(self, v): return self.oy - v * self.k

    def poly(self, pts, cls):
        self.p.append(f'<polygon class="{cls}" points="' + " ".join(f"{self.X(x):.1f},{self.Y(y):.1f}" for x, y in pts) + '"/>')

    def rect(self, x0, x1, y0, y1, cls):
        self.poly([(x0, y0), (x1, y0), (x1, y1), (x0, y1)], cls)

    def circle(self, x, y, d, cls):
        self.p.append(f'<circle class="{cls}" cx="{self.X(x):.1f}" cy="{self.Y(y):.1f}" r="{d / 2 * self.k:.1f}"/>')

    def line(self, x0, y0, x1, y1, cls="hid"):
        self.p.append(f'<line class="{cls}" x1="{self.X(x0):.1f}" y1="{self.Y(y0):.1f}" x2="{self.X(x1):.1f}" y2="{self.Y(y1):.1f}"/>')

    def path(self, pts, cls):
        self.p.append(f'<polyline class="{cls}" points="' + " ".join(f"{self.X(x):.1f},{self.Y(y):.1f}" for x, y in pts) + '"/>')

    def text(self, px, py, s, cls="n", anchor="start"):
        self.p.append(f'<text class="{cls}" x="{px:.1f}" y="{py:.1f}" text-anchor="{anchor}">{s}</text>')

    def note(self, x, y, px, py, s, anchor="start"):
        """Leader from model point (x, y) to a label at pixel (px, py)."""
        self.p.append(f'<line class="ext" style="stroke:#888" x1="{self.X(x):.1f}" y1="{self.Y(y):.1f}" x2="{px:.1f}" y2="{py - 4:.1f}"/>')
        self.text(px + (4 if anchor == "start" else -4), py, s, "n", anchor)

    def dim_h(self, x0, x1, y, py, label=None):
        """Horizontal dimension between model x0 and x1 (features at model height y), drawn at pixel row py."""
        for x in (x0, x1):
            self.p.append(f'<line class="ext" x1="{self.X(x):.1f}" y1="{self.Y(y):.1f}" x2="{self.X(x):.1f}" y2="{py + (5 if py > self.Y(y) else -5):.1f}"/>')
        self.p.append(f'<line class="dim" marker-start="url(#a)" marker-end="url(#a)" x1="{self.X(x0):.1f}" y1="{py:.1f}" x2="{self.X(x1):.1f}" y2="{py:.1f}"/>')
        self.text((self.X(x0) + self.X(x1)) / 2, py - 5, label or mm(abs(x1 - x0)), "t", "middle")

    def dim_v(self, y0, y1, x, px, label=None, side="left"):
        for y in (y0, y1):
            self.p.append(f'<line class="ext" x1="{self.X(x):.1f}" y1="{self.Y(y):.1f}" x2="{px + (5 if px > self.X(x) else -5):.1f}" y2="{self.Y(y):.1f}"/>')
        self.p.append(f'<line class="dim" marker-start="url(#a)" marker-end="url(#a)" x1="{px:.1f}" y1="{self.Y(y0):.1f}" x2="{px:.1f}" y2="{self.Y(y1):.1f}"/>')
        tx = px - 6 if side == "left" else px + 6
        self.text(tx, (self.Y(y0) + self.Y(y1)) / 2 + 4, label or mm(abs(y1 - y0)), "t", "end" if side == "left" else "start")

    def save(self, name, title):
        out = (f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {self.w} {self.h}" width="{self.w}" height="{self.h}">'
               f'{STYLE}<rect class="bg" width="{self.w}" height="{self.h}"/>'
               f'<text class="h" x="16" y="26">{title}</text>' + "".join(self.p) + "</svg>\n")
        with open(os.path.join(HERE, name), "w") as f:
            f.write(out)


def mirror(pts):
    return pts + [(-x, y) for x, y in reversed(pts)]


def ring_side(d, cls="pr"):
    """The finger ring as seen in the x-z section (its hole faces the viewer)."""
    d.circle(RING_R, RING_Z, RING_OD, cls)
    d.circle(RING_R, RING_Z, RING_ID, "void")


def draw_elevation():
    k = 2.6
    d = Svg(680, 790, 330, 730, k)
    d.line(0, -6, 0, TOTAL_H + 8, "cl")
    ring_side(d)
    d.poly(mirror(bowl_profile()), "pr")
    d.poly(mirror(cap_profile()), "pr")
    d.rect(-TUBE_OD / 2, TUBE_OD / 2, Z_NECK, Z_TUBE_TOP, "br")
    d.rect(-TUBE_OD / 2, TUBE_OD / 2, Z_TUBE_TOP, Z_COLLAR, "blk")
    d.rect(-TUBE_OD / 2, TUBE_OD / 2, Z_COLLAR, Z_DIFF, "br")
    d.rect(-TUBE_OD / 2, TUBE_OD / 2, Z_DIFF, TOTAL_H, "df")
    d.line(-R_RIM, Z_SEAM, R_RIM, Z_SEAM, "w2")
    d.line(-90, 0, 90, 0, "w2")
    # dimensions
    d.dim_v(0, TOTAL_H, -R_RIM, 130, f"{mm(TOTAL_H)} overall")
    d.dim_v(0, Z_SEAM, R_RIM, 520, mm(Z_SEAM), "right")
    d.dim_v(0, Z_NECK, R_RIM, 560, mm(Z_NECK), "right")
    d.dim_v(Z_NECK, Z_TUBE_TOP, TUBE_OD / 2, 410, f"{mm(Z_TUBE_TOP - Z_NECK)} stem showing", "right")
    d.dim_v(Z_COLLAR, Z_DIFF, TUBE_OD / 2, 410, f"{mm(COLLAR_L)} touch collar", "right")
    d.dim_v(Z_DIFF, TOTAL_H, TUBE_OD / 2, 410, f"{mm(DIFF_L)} diffuser", "right")
    d.dim_h(-R_RIM, R_RIM, Z_SEAM, d.Y(0) + 34, f"Ø{mm(BASE_D)} rim")
    d.dim_h(-R_BOT, R_BOT, 0, d.Y(0) + 14, f"Ø{mm(2 * R_BOT)} foot")
    d.note(TUBE_OD / 2, 150, 380, d.Y(150), f"Ø{mm(TUBE_OD)} (3/8″) brass tube")
    d.note(TUBE_OD / 2, Z_TUBE_TOP + 0.5, 380, d.Y(Z_TUBE_TOP) + 16, f"{mm(GAP_L)} insulating flange (coupler)")
    d.note(RING_R + 8, RING_Z + 6, 480, d.Y(RING_Z) - 30, f"finger ring Ø{mm(RING_OD)} × {mm(RING_W)}")
    d.note(-bowl_r(USB_Z), USB_Z, 170, d.Y(USB_Z) + 34, "USB-C window on this side", "end")
    d.note(-30, Z_SEAM, 170, d.Y(Z_SEAM) - 30, "seam at the rim", "end")
    d.save("candlestick-elevation.svg", "LED candlestick: elevation (mm)")


def base_section(d):
    """Section on the x-z plane through the base, shared by two drawings."""
    bo = bowl_profile()
    inner = [(bowl_r(FLOOR_T) - WALL, FLOOR_T)] + [(r - WALL, z) for r, z in bo if z > FLOOR_T]
    lipr = R_RIM - WALL + LIP_T
    for s in (1, -1):
        wall = bo + [(lipr, Z_SEAM), (lipr, Z_SEAM + LIP_H), (R_RIM - WALL, Z_SEAM + LIP_H)] + list(reversed(inner))
        d.poly([(s * r, z) for r, z in wall], "cut")
    d.rect(-R_BOT, R_BOT, 0, FLOOR_T, "cut")
    cp = cap_profile()
    sock = (TUBE_OD + TUBE_SOCKET_CLR) / 2
    for s in (1, -1):
        half = [(WIRE_HOLE_D / 2, Z_SEAM)] + cp + [(sock, Z_NECK), (sock, Z_TUBE_SEAT), (WIRE_HOLE_D / 2, Z_TUBE_SEAT)]
        d.poly([(s * r, z) for r, z in half], "cut")
    ring_side(d, "cut")
    # screw column, counterbore, insert (the +x column lies on the section plane)
    cx = COLS[0][0]
    d.rect(cx - COL_D / 2, cx + COL_D / 2, FLOOR_T, Z_SEAM, "cut")
    d.rect(cx - M3_CLEAR / 2, cx + M3_CLEAR / 2, M3_HEAD_H, Z_SEAM, "void")
    d.rect(cx - M3_HEAD_D / 2, cx + M3_HEAD_D / 2, 0, M3_HEAD_H, "void")
    d.rect(cx - INSERT_D / 2, cx + INSERT_D / 2, Z_SEAM, Z_SEAM + INSERT_DEPTH, "br")
    # tube, electronics
    d.rect(-TUBE_OD / 2, -TUBE_ID / 2, Z_TUBE_SEAT, Z_NECK + 14, "br")
    d.rect(TUBE_ID / 2, TUBE_OD / 2, Z_TUBE_SEAT, Z_NECK + 14, "br")
    d.rect(BOARD_USB_X, BOARD_USB_X + BOARD_L, BOARD_Z0, BOARD_Z0 + PCB_T, "pcb")
    d.rect(BOARD_USB_X, BOARD_USB_X + 7.5, BOARD_Z0 + PCB_T, BOARD_Z0 + PCB_T + 3.2, "blk")
    d.rect(BOARD_USB_X + 30, BOARD_USB_X + 55, BOARD_Z0 + PCB_T, BOARD_Z0 + PCB_T + 3.2, "blk")
    d.rect(BATT_X0, BATT_X0 + BATT[0], Z_SHELF, Z_SHELF + BATT[2], "bat")
    d.line(RAIL_X[0], Z_SHELF, RAIL_X[1], Z_SHELF, "hid")
    d.rect(-R_RIM - 2, BOARD_USB_X - 0.2, USB_Z - USB_H / 2, USB_Z + USB_H / 2, "nos")
    for z in (USB_Z - USB_H / 2, USB_Z + USB_H / 2):
        d.line(-bowl_r(z), z, -(bowl_r(z) - WALL), z, "w2")
    d.path([(BOARD_USB_X + 50, BOARD_Z0 + PCB_T + 3.2), (BATT_X0 + BATT[0] + 2, 14), (BATT_X0 + BATT[0] + 2, 20),
            (2, 20.6), (0.8, Z_TUBE_SEAT), (0.8, Z_NECK + 14)], "wire")


def draw_base_section():
    k = 6.0
    d = Svg(1100, 620, 520, 520, k)
    d.line(0, -5, 0, Z_NECK + 18, "cl")
    base_section(d)
    d.line(-70, 0, 70, 0, "w2")
    d.dim_h(-R_RIM, R_RIM, Z_SEAM, d.Y(0) + 62, f"Ø{mm(BASE_D)}")
    d.dim_h(-R_BOT, R_BOT, 0, d.Y(0) + 34, f"Ø{mm(2 * R_BOT)}")
    d.dim_v(0, Z_SEAM, -R_RIM, 150, f"{mm(Z_SEAM)} bowl")
    d.dim_v(Z_SEAM, Z_NECK, -R_RIM, 150, f"{mm(Z_NECK - Z_SEAM)} cap")
    d.dim_v(Z_TUBE_SEAT, Z_NECK, -R_NECK, 440, f"{mm(Z_NECK - Z_TUBE_SEAT)} tube socket", "left")
    d.dim_v(0, FLOOR_T, R_BOT, 830, f"{mm(FLOOR_T)} floor", "right")
    d.dim_h(-R_NECK, R_NECK, Z_NECK - 2, d.Y(Z_NECK) - 96, f"Ø{mm(NECK_D)} neck")
    d.note(16, cone_z(16) - 2, 700, d.Y(50), f"cone {mm(CONE_DEG)}° into an R{mm(FLARE_R)} flare")
    d.note(COLS[0][0], Z_SEAM + 3, 860, d.Y(34), "M3 heat-set insert")
    d.note(COLS[0][0], 10, 860, d.Y(12), f"column Ø{mm(COL_D)}, M3×{mm(SCREW_L)} from below")
    d.note(R_RIM - WALL + 0.7, Z_SEAM + 1, 860, d.Y(25), "lip and groove register the joint")
    d.note(BATT_X0 + 12, Z_SHELF + 4, 250, d.Y(48), f"LiPo {mm(BATT[2])} × {mm(BATT[1])} × {mm(BATT[0])} on the rails", "end")
    d.note(BOARD_USB_X + 20, BOARD_Z0 + 1, 250, d.Y(-6) + 50, "FireBeetle on 1 mm foam tape", "end")
    d.note(-R_RIM + 3, USB_Z, 200, d.Y(USB_Z) + 30, f"USB-C window {mm(USB_W)} × {mm(USB_H)}", "end")
    d.note(0.8, Z_NECK + 8, 600, d.Y(Z_NECK + 12), "wires up the tube: LED +, LED −, touch")
    d.note(RING_R, RING_Z + RING_OD / 2, 800, d.Y(Z_NECK), f"ring sunk {mm(RING_SINK)} into the cone")
    d.save("candlestick-base-section.svg", "Base: section through the USB window and the +X screw column (mm)")


def draw_plan():
    k = 5.5
    d = Svg(760, 700, 380, 360, k)
    d.circle(0, 0, BASE_D, "pr")
    d.circle(0, 0, 2 * (R_RIM - WALL), "void")
    d.circle(0, 0, 2 * (bowl_r(FLOOR_T) - WALL), "hid")
    d.line(-R_RIM - 6, 0, R_RIM + 6, 0, "cl")
    d.line(0, -R_RIM - 6, 0, R_RIM + 6, "cl")
    d.rect(BOARD_USB_X, BOARD_USB_X + BOARD_L, -BOARD_W / 2, BOARD_W / 2, "pcb")
    d.rect(BOARD_USB_X - 1, BOARD_USB_X + 7, -4.5, 4.5, "blk")
    half = BOARD_W / 2 + BOARD_CLR
    for s in (1, -1):
        y0, y1 = sorted((s * half, s * (half + RAIL_T)))
        d.rect(RAIL_X[0], RAIL_X[1], y0, y1, "cut")
    ex = BOARD_USB_X + BOARD_L + BOARD_CLR
    d.rect(ex, ex + 2, -6, 6, "cut")
    d.poly([(BATT_X0, -BATT[1] / 2), (BATT_X0 + BATT[0], -BATT[1] / 2), (BATT_X0 + BATT[0], BATT[1] / 2), (BATT_X0, BATT[1] / 2)], "hid")
    for x, y in COLS:
        d.circle(x, y, COL_D, "cut")
        d.circle(x, y, M3_CLEAR, "void")
    d.rect(-R_RIM - 1, BOARD_USB_X, -USB_W / 2, USB_W / 2, "void")
    d.rect(RING_R - RING_OD / 2, RING_R + RING_OD / 2, -RING_W / 2, RING_W / 2, "hid")
    d.circle(0, 0, WIRE_HOLE_D, "hid")
    d.dim_h(-R_RIM, R_RIM, 0, d.Y(-R_RIM) + 36, f"Ø{mm(BASE_D)}")
    d.dim_h(BOARD_USB_X, BOARD_USB_X + BOARD_L, BOARD_W / 2, d.Y(R_RIM) - 20, f"board {mm(BOARD_L)} × {mm(BOARD_W)}")
    d.dim_h(0, COLS[0][0], 0, d.Y(-R_RIM) + 14, f"{mm(COLS[0][0])} to each column")
    d.note(BATT_X0 + 4, BATT[1] / 2, 60, 80, f"battery outline {mm(BATT[0])} × {mm(BATT[1])}, above the board")
    d.note(RAIL_X[1] - 4, -half - 1, 520, 640, f"rails {mm(RAIL_T)} thick, tops at {mm(Z_SHELF)}")
    d.note(RING_R, RING_W / 2, 600, 250, "finger ring (on the cap)")
    d.note(-R_RIM + 2, -USB_W / 2, 50, 440, "USB-C window")
    d.note(ex + 1, 5, 560, 300, "end stop")
    d.note(COLS[1][0], COLS[1][1], 470, 90, f"3 columns Ø{mm(COL_D)}, Ø{mm(M3_CLEAR)} through")
    d.note(0, 0, 500, 420, f"Ø{mm(WIRE_HOLE_D)} wire hole in the cap, over the battery")
    d.save("candlestick-base-plan.svg", "Bowl: plan from above, cap removed (mm)")


def draw_top():
    k = 11.0
    z0 = Z_TUBE_TOP - 22
    d = Svg(720, 960, 300, 915 + z0 * k, k)
    ro, ri = TUBE_OD / 2, TUBE_ID / 2
    rs, rn, rb = SPIGOT_D / 2, NOSE_D / 2, BORE_D / 2
    L = Z_DIFF
    d.line(0, z0 - 2, 0, TOTAL_H + 3, "cl")
    # diffuser (section)
    rc = ro - DIFF_WALL
    zc = L + 1.5 + (rc - rb)
    for s in (1, -1):
        d.poly([(s * r, z) for r, z in [(rb, L - COLLAR_L - NOSE_L), (rn, L - COLLAR_L - NOSE_L), (rn, L - COLLAR_L),
                                        (rs, L - COLLAR_L), (rs, L), (ro, L), (ro, TOTAL_H - 1.5), (ro - 1.5, TOTAL_H), (0, TOTAL_H),
                                        (0, TOTAL_H - DIFF_WALL), (rc, TOTAL_H - DIFF_WALL), (rc, zc), (rb, L + 1.5)]], "df")
    # coupler
    for s in (1, -1):
        d.poly([(s * r, z) for r, z in [(rn + 0.1, Z_TUBE_TOP - COUPLER_SPIGOT_L), (rs, Z_TUBE_TOP - COUPLER_SPIGOT_L),
                                        (rs, Z_TUBE_TOP), (ro, Z_TUBE_TOP), (ro, Z_COLLAR), (rn + 0.1, Z_COLLAR)]], "blk")
    # brass
    for s in (1, -1):
        a, b = sorted((s * ri, s * ro))
        d.rect(a, b, Z_COLLAR, L, "br")
        d.rect(a, b, z0, Z_TUBE_TOP, "br")
    # filament + wires
    d.rect(-1.1, 1.1, L + 7, L + 32, "led")
    d.path([(-0.7, L + 7), (-0.7, z0)], "wire")
    d.path([(0.7, L + 7), (0.7, z0)], "wire")
    d.path([(ri, Z_COLLAR + 3), (rb - 0.3, Z_COLLAR + 3), (1.6, Z_COLLAR - 2), (1.6, z0)], "w2")
    d.circle(ri - 0.3, Z_COLLAR + 3, 1.0, "blk")
    d.dim_v(L, TOTAL_H, -ro, 150, f"{mm(DIFF_L)} diffuser")
    d.dim_v(Z_COLLAR, L, -ro, 150, f"{mm(COLLAR_L)} collar")
    d.dim_v(Z_TUBE_TOP, Z_COLLAR, -ro, 110, f"{mm(GAP_L)}")
    d.dim_v(Z_TUBE_TOP - COUPLER_SPIGOT_L, Z_TUBE_TOP, -ro, 150, f"{mm(COUPLER_SPIGOT_L)} into the tube")
    d.dim_h(-ro, ro, TOTAL_H, d.Y(TOTAL_H) - 22, f"Ø{mm(TUBE_OD)}")
    d.note(rc, L + 30, 420, d.Y(L + 34), f"wall {mm(DIFF_WALL)}, white or natural filament")
    d.note(1.1, L + 20, 420, d.Y(L + 22), "25 mm single-ended LED filament, leads down")
    d.note(ro, L - 5, 420, d.Y(L - 4), "brass collar = touch electrode")
    d.note(ri - 0.3, Z_COLLAR + 3, 420, d.Y(Z_COLLAR + 1), "touch wire soldered inside the collar,")
    d.text(424, d.Y(Z_COLLAR + 1) + 14, f"led through the {mm(SLOT_W)} mm slot into the bore")
    d.note(ro, Z_TUBE_TOP + 0.5, 420, d.Y(Z_TUBE_TOP - 3), "coupler flange keeps collar and stem apart")
    d.note(rn, L - COLLAR_L - 3, 420, d.Y(Z_TUBE_TOP - 7), f"Ø{mm(NOSE_D)} nose glued into the coupler")
    d.note(ro, z0 + 4, 420, d.Y(z0 + 4), f"stem tube, Ø{mm(TUBE_ID)} inside, wired to GND")
    d.save("candlestick-top-detail.svg", "Top of the stem: section through diffuser, collar and coupler (mm)")


def draw_wiring():
    d = Svg(820, 470, 0, 470, 1.0)
    P = d.p
    def box_(x, y, w, h, label, cls="pr"):
        P.append(f'<rect class="{cls}" x="{x}" y="{y}" width="{w}" height="{h}" rx="4"/>')
        d.text(x + w / 2, y + h / 2 + 4, label, "t", "middle")
    def wire(pts, cls="w2"):
        P.append(f'<polyline class="{cls}" points="' + " ".join(f"{x},{y}" for x, y in pts) + '"/>')
    def dot(x, y):
        P.append(f'<circle cx="{x}" cy="{y}" r="3" fill="#333"/>')
    box_(40, 90, 170, 300, "", "pcb")
    d.text(125, 112, "FireBeetle 2 ESP32-E", "t", "middle")
    for y, s in ((150, "3V3"), (210, "GPIO25"), (270, "GPIO13 (touch T4)"), (330, "GND"), (372, "PH2.0 battery")):
        d.text(202, y + 4, s, "n", "end")
    box_(40, 400, 170, 40, "LiPo 3.7 V 2000 mAh", "bat")
    wire([(125, 390), (125, 400)])
    # LED branch
    wire([(210, 150), (300, 150)])
    box_(300, 138, 70, 24, "R1 22 Ω")
    wire([(370, 150), (470, 150)])
    box_(470, 132, 150, 36, "LED filament 3 V", "led")
    d.text(476, 126, "+", "t"); d.text(606, 126, "−", "t")
    wire([(620, 150), (700, 150), (700, 196)])
    # transistor
    P.append('<circle cx="700" cy="216" r="20" fill="#fff" stroke="#333" stroke-width="1.5"/>')
    d.text(700, 220, "Q1", "t", "middle")
    d.text(728, 220, "2N3904", "n")
    d.text(706, 192, "C", "n"); d.text(706, 250, "E", "n"); d.text(668, 208, "B", "n")
    wire([(700, 236), (700, 330), (210, 330)])
    wire([(210, 210), (300, 210)])
    box_(300, 198, 70, 24, "R2 1 kΩ")
    wire([(370, 210), (680, 210)])
    dot(560, 210)
    wire([(560, 210), (560, 250)])
    box_(525, 250, 70, 24, "R3 10 kΩ")
    wire([(560, 274), (560, 330)])
    dot(560, 330); dot(700, 330)
    # touch
    wire([(210, 270), (420, 270)], "wire")
    box_(420, 256, 90, 28, "brass collar", "br")
    # stem ground
    wire([(450, 330), (450, 372)])
    dot(450, 330)
    box_(405, 372, 90, 28, "stem tube", "br")
    d.text(300, 62, "R1 sets the LED current: start at 22 Ω, measure, and stay under 50 mA.", "n")
    d.text(300, 78, "R3 holds the LED off while the ESP32 sleeps. The stem is grounded so only the collar reads as a touch.", "n")
    d.save("candlestick-wiring.svg", "Wiring")


def draw_all():
    draw_elevation(); draw_base_section(); draw_plan(); draw_top(); draw_wiring()


def main():
    print(f"lamp {TOTAL_H:.0f} tall, rim {BASE_D:.0f}, foot {2 * R_BOT:.1f};  stem tube cut {TUBE_L:.1f} "
          f"({TUBE_L / 25.4:.2f} in), collar {COLLAR_L:.1f};  neck fillet meets the neck at z={FLARE_ZC:.1f}")
    print(f"{'part':<10} {'tris':>6} {'vol cm3':>8} {'genus':>5}  {'bbox (mm)':<24} watertight")
    ok = True
    for name, (fn, rgb) in PARTS.items():
        man = fn()
        tm = to_trimesh(man)
        tm.apply_translation(-tm.bounds[0])
        dims = " x ".join(f"{v:.1f}" for v in (tm.bounds[1] - tm.bounds[0]))
        wt = tm.is_watertight and tm.is_winding_consistent and tm.volume > 0
        ok &= wt
        print(f"{name:<10} {len(tm.faces):>6} {tm.volume / 1000:>8.1f} {man.genus():>5}  {dims:<24} {'yes' if wt else 'NO <-- BAD'}")
        tm.export(os.path.join(HERE, f"{name}.stl"))
        render_preview([(tm, rgb)], name)
    d = dummies()
    brass, white, dark = (0.80, 0.64, 0.25), (0.96, 0.93, 0.82), (0.2, 0.2, 0.22)
    asm = [(to_trimesh(part_bowl()), brass), (to_trimesh(part_cap()), brass),
           (to_trimesh(d["tube"]), brass), (to_trimesh(d["collar"]), brass),
           (to_trimesh(cyl(0, 0, Z_TUBE_TOP, Z_COLLAR, TUBE_OD)), dark),
           (to_trimesh(cyl(0, 0, Z_DIFF, TOTAL_H, TUBE_OD)), white)]
    render_preview(asm, "assembly", elev=14, azim=-62, size=(6, 9))
    opened = [(to_trimesh(part_bowl()), brass), (to_trimesh(d["board"]), (0.2, 0.5, 0.3)),
              (to_trimesh(d["battery"].translate((0, 0, 22))), (0.85, 0.65, 0.15)),
              (to_trimesh(part_cap().translate((0, 0, 60))), brass)]
    render_preview(opened, "base_exploded", elev=32, azim=-120, size=(6, 8))
    draw_all()
    problems = fit_check()
    for p in problems:
        print("FIT:", p)
    ok &= not problems
    print("\nAll parts watertight, fit check clean." if ok else "\nSOME CHECKS FAILED")
    return 0 if ok else 1


if __name__ == "__main__":
    raise SystemExit(main())
