#!/usr/bin/env python3
"""
Parametric STL generator for the 3D-printed aids of the Coopered Fly-Rod Tube
(src/content/docs/docs/woodworking/projects/rod-tube.md). All dimensions in mm; parts export
in print orientation as rod_tube_*.stl with previews in previews/.

Everything follows the tube's geometry: an 8-stave octagon whose smallest clear round
(flat to flat) is ID_IN. Change the parameter block (and ID in tools/woodworking/
rod_tube_calc.py and rod_tube_drawings.py to match) and re-run.

Requirements:  pip install manifold3d trimesh numpy matplotlib
Usage:         python3 generate_rod_tube_stls.py

Print in PETG (PLA creeps under clamp pressure and softens in a hot car), 0.2 mm layers,
4 perimeters, 30-40% infill, 100% around the drill-guide holes. PRINT ONE gauge first,
measure it with calipers and adjust FIT (mm per side) for your printer.
"""
import math
import os
import numpy as np
from manifold3d import Manifold, CrossSection

from generate_woodworking_stls import box, cyl_z, to_trimesh, render_preview, HERE, IN

# -- the tube (inches; must match tools/woodworking/rod_tube_calc.py) --------------
ID_IN = 2.200            # smallest clear round, flat to flat
WALL_IN = 5 / 16         # finished body wall
WELT_IN = 5 / 16         # welt (end band) wall
SPIGOT_CLR_IN = 0.030    # lid spigot is this much smaller than the bore, across flats
MAG_D_IN = 0.375
MAG_R_IN = ID_IN / 2 + WALL_IN       # pockets sit on the body / welt glue line

# -- printing -----------------------------------------------------------------------
FIT = 0.20               # mm clearance per side for slip fits (tune after one test print)
SAW_BODY_IN = ID_IN + 2 * WALL_IN + 0.01   # as-planed body across flats, plus 0.01" for the saddle bore
SAW_WELT_IN = ID_IN + 2 * WALL_IN + 2 * WELT_IN + 0.01

SEG = 96


def mm(inches):
    return inches * IN


def octagon_z(h, af):
    """Octagonal prism, flats on the axes, `af` across flats (mm), height h."""
    r = af / 2 / math.cos(math.radians(22.5))
    return Manifold.cylinder(h, r, r, 8).rotate((0, 0, 22.5))


def ring_round(h, d_out, af_in):
    return cyl_z(h, d_out) - octagon_z(h + 2, af_in).translate((0, 0, -1))


# ---------------------------------------------------------------------------
def saddle_half(af_in):
    """Half of a split clamp saddle: an octagonal bore, round outside with two lips that keep a
    hose clamp in place. A round hose clamp bears on an octagon only at its corners and bruises
    them; the saddle spreads the load over the faces. Printed flat on its cut face."""
    af = mm(af_in)
    corner = af / math.cos(math.radians(22.5))
    od = corner + 2 * 5.0
    w = 19.0                                       # 3/4" wide
    m = ring_round(w, od, af)
    for z0 in (0, w - 2.0):                        # 2 mm lips, 2.5 mm high, either side of the clamp
        m += (cyl_z(2.0, od + 5.0) - octagon_z(4, af).translate((0, 0, -1))).translate((0, 0, z0))
    m ^= box(-200, 200, 0, 200, -1, w + 1)         # keep y >= 0: one half
    return m


def part_saddle_body():
    return saddle_half(SAW_BODY_IN)


def part_saddle_welt():
    return saddle_half(SAW_WELT_IN)


def part_v_cradle():
    """90-degree V block: an octagon with its flats on the axes sits on two faces in a 90-degree V
    (the bottom flat floats in the relief). 3" long x 4" wide x 2.4" tall; cut from a plain block."""
    L, W, Hh = mm(3.0), mm(4.0), mm(2.4)
    half = W / 2                                   # 90-degree V: the depth equals the half opening
    relief = 3.0                                   # flat at the bottom of the V, so the apex is not a stress line
    x0 = W / 2
    prof = CrossSection([[(0, 0), (W, 0), (W, Hh), (x0 + half, Hh),
                          (x0 + relief / 2, Hh - half + relief / 2), (x0 - relief / 2, Hh - half + relief / 2),
                          (x0 - half, Hh), (0, Hh)]])                              # counter-clockwise U profile
    return Manifold.extrude(prof, L).rotate((90, 0, 0)).translate((0, L, 0))


def part_end_gauge():
    """Go-gauge: an octagon exactly one bore wide (minus FIT). Push it into each end of the glued tube to hold
    the octagon regular while it is clamped; it also checks the bore afterwards. Finger hole to pull it out."""
    af = mm(ID_IN) - 2 * FIT
    m = octagon_z(mm(0.625), af)
    m -= cyl_z(mm(0.625) + 2, mm(1.25), 64).translate((0, 0, -1))
    return m


def part_outside_gauge():
    """Slit ring that checks the planed body: it should just slip over the 2 5/8-class outside."""
    af = mm(SAW_BODY_IN)
    m = ring_round(mm(0.5), af / math.cos(math.radians(22.5)) + 8.0, af)
    m -= box(-0.6, 0.6, 0, 200, -1, mm(0.5) + 1)             # a 1.2 mm slit so the ring can flex
    return m


def part_swab():
    """Octagonal swab / sanding stick body: wrap damp cotton (or flat-backed sandpaper) round it and push
    it through the bore on a 3/4" dowel. A slot tucks the end of the rag."""
    af = mm(ID_IN - 0.10)
    m = octagon_z(mm(1.5), af)
    m -= cyl_z(mm(1.5) + 2, mm(0.75) + 0.4, 64).translate((0, 0, -1))
    m -= box(-6.0, 6.0, -1.2, 1.2, mm(1.5) / 2 - 3.0, mm(1.5) + 1)   # rag-tuck slot across the end
    return m


def part_drill_guide():
    """Magnet drill guide: one plate that registers on the tube end (male plug in the bore) and on the lid
    (socket over the spigot), with two 3/8" pocket holes 180 degrees apart at the glue-line radius, so the four
    pockets line up exactly. Set a stop collar on the bit to plate thickness + pocket depth."""
    plate_af = mm(ID_IN + 2 * WALL_IN + 2 * WELT_IN)
    t = mm(1.0)
    plug_af = mm(ID_IN) - 2 * FIT
    spigot_af = mm(ID_IN - SPIGOT_CLR_IN) + 2 * FIT
    socket_depth = mm(0.8)
    plug_h = mm(0.75)
    m = octagon_z(t, plate_af)
    m += octagon_z(plug_h, plug_af).translate((0, 0, -plug_h))          # side A plug, into the tube bore
    m -= octagon_z(socket_depth + 1, spigot_af).translate((0, 0, t - socket_depth))   # side B socket over the spigot
    for sy in (-1, 1):
        m -= cyl_z(t + plug_h + 2, mm(MAG_D_IN) + 0.4, 64).translate((0, sy * mm(MAG_R_IN), -plug_h - 1))
    return m.translate((0, 0, plug_h))


def part_angle_gauges():
    """Two quick-check gauges on one plate: a 135-degree inside corner (two adjacent faces of the bore or the
    test ring) and a 22.5-degree bevel gauge for a stave edge. The digital angle gauge stays the reference."""
    t = 4.0
    c, sn = math.cos(math.radians(22.5)), math.sin(math.radians(22.5))
    plate = box(0, 70, 0, 55, 0, t)
    # a true 135-degree V notch: apex at (35, 12), arms rising 22.5 degrees from horizontal (angle between them 135)
    ax, ay, L = 35.0, 12.0, 60.0
    notch = Manifold.extrude(CrossSection([[(ax, ay), (ax + L * c, ay + L * sn), (ax + L * c, 60),
                                            (ax - L * c, 60), (ax - L * c, ay + L * sn)]]), t + 2).translate((0, 0, -1))
    wedge = Manifold.extrude(CrossSection([[(0, 0), (70, 0), (70, 70 * math.tan(math.radians(22.5)))]]), t)
    return (plate - notch) + wedge.translate((80, 0, 0))


def part_spacer():
    """Short-rod spacer ring: takes up clear length for a shorter rod. Felt the ends. A wine cork does the same."""
    af = mm(ID_IN - 0.05)
    m = octagon_z(mm(0.5), af)
    m -= cyl_z(mm(0.5) + 2, mm(ID_IN) * 0.68, 64).translate((0, 0, -1))
    return m


PARTS = {
    "rod_tube_saddle_body": (part_saddle_body, 14),
    "rod_tube_saddle_welt": (part_saddle_welt, 2),
    "rod_tube_v_cradle":    (part_v_cradle, 4),
    "rod_tube_end_gauge":   (part_end_gauge, 2),
    "rod_tube_outside_gauge": (part_outside_gauge, 1),
    "rod_tube_swab":        (part_swab, 1),
    "rod_tube_drill_guide": (part_drill_guide, 1),
    "rod_tube_angle_gauges": (part_angle_gauges, 1),
    "rod_tube_spacer":      (part_spacer, 1),
}


def main():
    print(f"{'part':<24} {'qty':>3} {'tris':>6} {'vol cm3':>8}  {'bbox (mm)':<26} watertight")
    ok = True
    for name, (fn, qty) in PARTS.items():
        man = fn()
        tm = to_trimesh(man)
        tm.apply_translation(-tm.bounds[0])
        bb = tm.bounds
        dims = " x ".join(f"{d:.1f}" for d in (bb[1] - bb[0]))
        wt = tm.is_watertight and tm.is_winding_consistent and tm.volume > 0
        ok &= wt
        print(f"{name:<24} {qty:>3} {len(tm.faces):>6} {tm.volume / 1000:>8.1f}  {dims:<26} {'yes' if wt else 'NO <-- BAD'}")
        tm.export(os.path.join(HERE, f"{name}.stl"))
        render_preview(tm, name)
    print("\nAll parts watertight." if ok else "\nSOME PARTS FAILED VALIDATION")
    return 0 if ok else 1


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