#!/usr/bin/env python3
"""
Parametric STL generator for the 3D-printed parts of the Western NC birdhouse plans
(src/content/docs/docs/woodworking/birdhouse-plans.md): entrance portals in three hole
sizes (flush and tunnel versions), the quarter-turn door latch, and the pivot and fixed caps.
All dimensions in mm (inches x 25.4); parts export in print orientation as birdhouse_*.stl
with previews in previews/.

The numbers mirror the PRINTED block in tools/woodworking/birdhouse_drawings.py; change
them in both places and re-run both scripts.

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

Print in ASA (best outdoors) or PETG, never PLA: a south-facing box in the sun gets hot
enough to soften it, and PLA is not UV-stable. Light grey, white or natural; black soaks up
heat. 0.2 mm layers, 4 perimeters, 40% infill. PRINT ONE portal first and check it in a
scrap of the real wood: adjust FIT (mm per side) if it is tight or loose.
"""
import math
import os
from manifold3d import Manifold, CrossSection

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

# -- design numbers (inches; must match tools/woodworking/birdhouse_drawings.py) ---------
PANEL_T = 0.75
PANEL_BIT_EXTRA = 3 / 8          # panel hole = entrance + this (a standard Forstner size)
FLANGE_T = 0.20
TUNNEL_PROJECT = 1.0
TUNNEL_WALL = 3 / 8
BEAD_W = 0.19                    # width of the raised bead ring on the flange face
LATCH_HUB, LATCH_W, LATCH_REACH, LATCH_T = 0.75, 0.5, 1.25, 0.20
CAP_FLANGE, CAP_BORE, CAP_PANEL_HOLE, CAP_FLANGE_T = 0.625, 0.18, 0.375, 0.12
GAP = 1 / 16

FIT = 0.20                       # mm clearance per side for the slip fit into the wood
SEG = 96

# (entrance in, flange OD in)
PORTALS = [(1.125, 2.375), (1.25, 2.375), (1.5, 2.75)]


def mm(v):
    return v * IN


def revolve(profile, seg=SEG):
    """Revolve an (r, z) polygon about the z axis (z up, print orientation)."""
    cs = CrossSection([[(r, z) for r, z in profile]])
    return Manifold.revolve(cs, seg)


def portal(hole_in, flange_in, tunnel):
    """Entrance portal, front face down on the bed (z = 0). Barrel goes into a Forstner hole of
    (entrance + 3/8 in), the flange sits on the panel face. The flush version is screwed on through
    four counterbored holes (#4 x 5/8 stainless); the tunnel version projects 1 in and is
    set in epoxy, so it needs no screws and prints without a bridge."""
    ri = mm(hole_in) / 2
    bit = mm(hole_in + PANEL_BIT_EXTRA)
    rb = bit / 2 - FIT                       # barrel outer radius, slip fit
    rf = mm(flange_in) / 2
    ft = mm(FLANGE_T)
    c = 0.8                                  # edge chamfer
    barrel = mm(PANEL_T) - 0.3
    pts = []
    if not tunnel:
        step = 1.6                           # the bead steps back 1.6 mm at a 45 degree chamfer
        rbead = rf - mm(BEAD_W)
        pts = [(ri + c, 0), (rbead, 0), (rbead + step, step), (rf - c, step), (rf, step + c),
               (rf, ft), (rb, ft), (rb, ft + barrel), (ri + c, ft + barrel), (ri, ft + barrel - c),
               (ri, c)]
    else:
        rt = ri + mm(TUNNEL_WALL)
        tp = mm(TUNNEL_PROJECT)
        ramp = rf - rt                       # 45 degree flare from the tunnel out to the flange
        z1 = tp + ramp
        pts = [(ri + c, 0), (rt - c, 0), (rt, c), (rt, tp), (rf - 0.01, z1), (rf, z1 + c),
               (rf, z1 + ft - 1.6), (rb, z1 + ft - 1.6), (rb, z1 + ft - 1.6 + barrel),
               (ri + c, z1 + ft - 1.6 + barrel), (ri, z1 + ft - 1.6 + barrel - c), (ri, c)]
    m = revolve(pts)
    if not tunnel:
        rs = (bit / 2 + rf) / 2              # screw circle, midway across the flange ring
        for k in range(4):
            a = math.radians(45 + 90 * k)
            x, y = rs * math.cos(a), rs * math.sin(a)
            m -= cyl_z(ft + 2, 3.2, 32).translate((x, y, -1))            # #4 clearance
            m -= cyl_z(2.2, 5.9, 32).translate((x, y, -0.01))            # pan-head pocket from the front face
    return m


def latch():
    """Quarter-turn latch: a stadium-shaped arm on a round hub, flat on the bed. Counterbores on the top."""
    w = mm(LATCH_W)
    reach = mm(LATCH_REACH)
    t = mm(LATCH_T)
    hub = mm(LATCH_HUB)
    m = cyl_z(t, hub, SEG)
    m += box(-w / 2, w / 2, 0, reach, 0, t)
    m += cyl_z(t, w, SEG).translate((0, reach, 0))
    m -= cyl_z(t + 2, 5.2, 48).translate((0, 0, -1))                       # #8 clearance
    m -= cyl_z(mm(0.12) + 1, 10.2, 48).translate((0, 0, t - mm(0.12)))     # #8 pan-head pocket
    ly = mm(1.0)
    m -= cyl_z(t + 2, 3.8, 48).translate((0, ly, -1))                      # #6 lock-screw clearance
    m -= cyl_z(mm(0.10) + 1, 7.6, 48).translate((0, ly, t - mm(0.10)))
    return m


def cap(length_in):
    """Flanged sleeve over a pivot or fixed-wall screw: outer face down, barrel up."""
    ft = mm(CAP_FLANGE_T)
    rb = mm(CAP_PANEL_HOLE) / 2 - FIT
    pts = [(0.0, 0), (mm(CAP_FLANGE) / 2 - 0.6, 0), (mm(CAP_FLANGE) / 2, 0.6), (mm(CAP_FLANGE) / 2, ft),
           (rb, ft), (rb, mm(length_in) + ft - 0.4), (rb - 0.4, mm(length_in) + ft), (0.0, mm(length_in) + ft)]
    m = revolve(pts)
    m -= cyl_z(mm(length_in) + ft + 2, mm(CAP_BORE), 48).translate((0, 0, -1))
    m -= cyl_z(mm(0.09) + 1, 9.4, 48).translate((0, 0, -1))                # #8 pan-head recess from the face
    return m


def part_portals():
    out = {}
    for hole, flange in PORTALS:
        tag = f"{round(hole * 1000):04d}"
        out[f"birdhouse_portal_{tag}_flush"] = (portal(hole, flange, False), 1)
        out[f"birdhouse_portal_{tag}_tunnel"] = (portal(hole, flange, True), 1)
    return out


def parts():
    p = part_portals()
    p["birdhouse_latch"] = (latch(), 1)
    p["birdhouse_cap_pivot"] = (cap(PANEL_T + GAP), 2)
    p["birdhouse_cap_fixed"] = (cap(PANEL_T), 2)
    return p


def main():
    print(f"{'part':<32} {'qty':>3} {'tris':>6} {'vol cm3':>8}  {'bbox (mm)':<26} watertight")
    ok = True
    for name, (man, qty) in parts().items():
        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:<32} {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())
