#!/usr/bin/env python
"""BRIM-016 / Top-hat flat-back keychain token (side-profile silhouette).

Source: r/3Drequests t3_1xg15cu (2026-10-26, /u/lamarus) — a small
top-hat keychain charm: side-profile silhouette like their sew-on
button reference (style only), flat back, ~4 mm total thickness with
details raised ~1 mm, support-free flat on the bed, keyring hole
3-4 mm at the top, ~25 mm wide and resizable in the slicer.
Provenance + verified negative: research/SHORTLIST.md C-12 (admitted
wake 275 before CAD).

What this is: ONE printed part, no assembly, no supports (proven by
slice, not asserted):
  - a 3 mm flat-backed side-profile top-hat silhouette (brim bar +
    slightly flared crown), 25 mm wide;
  - the BRIM slab and the HAT BAND raised +1 mm (the two details the
    ask names), total 4 mm;
  - an integral keyring loop at the top center, 3.5 mm hole, 2.25 mm
    ring wall, full base thickness.
Scale uniformly in the slicer; at 100 % the hole is 3.5 mm.

Design stance (house rule): a check that cannot fail is not a check.
D-checks are mesh-measured; N1 is a negative control on the
point-classifier itself (a point known to sit in solid material must
classify INSIDE, else the D4 hole check proves nothing).

DESIGN CONTRACT (mesh-measured, mm):
  D1 thickness : bounds z = [0, 4.0] (+/-0.05).
  D2 width     : bounds x extent = 25.0 (+/-0.1).
  D3 flat back : every downward face (normal_z < -0.5) lies at z=0
                 (+/-0.01), and their summed area equals the 2-D base
                 footprint (+/-2 %) — nothing overhangs, the back is
                 one plane.
  D4 keyring   : at z=1.5 the section classifies (0, YLOOP) as
                 OUTSIDE material (even crossings — it is the hole)
                 and the nearest section segment to the hole center
                 sits at r = 1.75 (+/-0.15) (hole dia 3.5).
  D5 band step : a +z ray footprint test — points on the band and on
                 the brim lie under 4 mm of part, a point on the bare
                 crown under 3 mm (measured by top-surface z at those
                 x,y via section at the point).
  D6 solid     : watertight, exactly one body, volume within 10 % of
                 the analytic footprint sum.
  N1 negative  : the D4 classifier run at (0, 12) (mid-crown, solid)
                 must return INSIDE (odd crossings); if it agrees
                 with the hole point the classifier is broken and
                 ALL_PASS must not print.
Slice gate (bin/slice, outside this script): zero supports, sane
temps, time/grams on the record before publishing.
"""
import numpy as np
import trimesh
from shapely.geometry import Polygon, box
from shapely.ops import unary_union
from pathlib import Path

ENG = dict(engine="manifold")
OUT = Path(__file__).parent

# --- parameters (mm) ---
WIDTH = 25.0          # overall brim width (the ask's ~25 mm)
BRIM_H = 4.0          # brim bar height in profile
BRIM_R = 1.2          # brim corner rounding
CROWN_BASE_HW = 7.2   # crown half-width where it meets the brim
CROWN_TOP_HW = 8.3    # crown half-width at the top (classic flare)
CROWN_TOP = 20.0      # crown top y
BAND_Y0, BAND_Y1 = BRIM_H, BRIM_H + 3.5   # hat band strip
LOOP_R_OUT = 4.0
HOLE_R = 1.75         # 3.5 mm hole
YLOOP = 22.5          # loop center (overlaps crown top by 1.5)
T_BASE = 3.0          # base thickness
T_RAISE = 1.0         # detail relief

def silhouette_parts():
    hw = WIDTH / 2.0
    brim = box(-hw + BRIM_R, BRIM_R, hw - BRIM_R, BRIM_H - BRIM_R).buffer(
        BRIM_R, resolution=24)
    crown = Polygon([(-CROWN_BASE_HW, BRIM_H - 1.0),
                     (CROWN_BASE_HW, BRIM_H - 1.0),
                     (CROWN_TOP_HW, CROWN_TOP),
                     (-CROWN_TOP_HW, CROWN_TOP)])
    loop = Polygon()  # built from a circle
    th = np.linspace(0, 2 * np.pi, 96, endpoint=False)
    loop = Polygon(np.column_stack([LOOP_R_OUT * np.cos(th),
                                    YLOOP + LOOP_R_OUT * np.sin(th)]))
    hole = Polygon(np.column_stack([HOLE_R * np.cos(th),
                                    YLOOP + HOLE_R * np.sin(th)]))
    return brim, crown, loop, hole

def build():
    brim, crown, loop, hole = silhouette_parts()
    base2d = unary_union([brim, crown, loop]).difference(hole)
    base = trimesh.creation.extrude_polygon(base2d, T_BASE)

    # raised details: the brim slab and the hat band, +1 mm on top
    band2d = crown.intersection(box(-10, BAND_Y0, 10, BAND_Y1))
    raised2d = unary_union([brim, band2d])
    raised = trimesh.creation.extrude_polygon(raised2d, T_RAISE)
    raised.apply_translation([0, 0, T_BASE])

    m = base.union(raised, **ENG)
    return m, base2d, raised2d

def classify(section_mesh, pt):
    """Crossing-number test at z-section: odd = inside material."""
    lines = section_mesh  # trimesh.path.Path2D via to_2D? use segments
    segs = lines
    x0, y0 = pt
    crossings = 0
    for (xa, ya), (xb, yb) in segs:
        if (ya > y0) != (yb > y0):
            xi = xa + (y0 - ya) * (xb - xa) / (yb - ya)
            if xi > x0:
                crossings += 1
    return crossings % 2 == 1, crossings

def seg2d(mesh, z):
    s = trimesh.intersections.mesh_plane(mesh, [0, 0, 1], [0, 0, z])
    return [((a[0], a[1]), (b[0], b[1])) for a, b in s]

def top_z_at(mesh, x, y):
    """Highest z of the part over (x, y) via two plane sections."""
    sx = trimesh.intersections.mesh_plane(mesh, [1, 0, 0], [x, 0, 0])
    best = None
    for a, b in sx:
        for t in np.linspace(0, 1, 9):
            p = a + t * (b - a)
            if abs(p[1] - y) < 0.35:
                best = p[2] if best is None else max(best, p[2])
    return best

def main():
    m, base2d, raised2d = build()
    results = []

    def check(name, ok, detail):
        results.append((name, bool(ok), detail))

    bz = m.bounds
    check("D1 thickness", abs(bz[0][2]) < 0.05 and abs(bz[1][2] - 4.0) < 0.05,
          f"z [{bz[0][2]:.3f}, {bz[1][2]:.3f}]")
    wx = bz[1][0] - bz[0][0]
    check("D2 width", abs(wx - WIDTH) < 0.1, f"x extent {wx:.3f}")

    down = m.face_normals[:, 2] < -0.5
    zmax_down = float(m.triangles[down][:, :, 2].max())
    a_down = float(m.area_faces[down].sum())
    check("D3 flat back", zmax_down < 0.01 and
          abs(a_down - base2d.area) / base2d.area < 0.02,
          f"down faces max z {zmax_down:.4f}, area {a_down:.1f} vs 2D {base2d.area:.1f}")

    segs = seg2d(m, 1.5)
    inside_hole, ch = classify(segs, (0.0, YLOOP))
    dmin = min(min(np.hypot(a[0] - 0, a[1] - YLOOP),
                   np.hypot(b[0] - 0, b[1] - YLOOP)) for a, b in segs)
    check("D4 keyring hole", (not inside_hole) and abs(dmin - HOLE_R) < 0.15,
          f"hole pt crossings {ch} (even=hole), nearest seg r {dmin:.3f}")

    z_band = top_z_at(m, 0.0, (BAND_Y0 + BAND_Y1) / 2)
    z_brim = top_z_at(m, WIDTH / 2 - 3.0, BRIM_H / 2)
    z_crown = top_z_at(m, 0.0, 14.0)
    check("D5 band step",
          z_band is not None and abs(z_band - 4.0) < 0.05 and
          z_brim is not None and abs(z_brim - 4.0) < 0.05 and
          z_crown is not None and abs(z_crown - 3.0) < 0.05,
          f"top z band {z_band} brim {z_brim} crown {z_crown}")

    vol_expect = base2d.area * T_BASE + raised2d.area * T_RAISE
    check("D6 solid", m.is_watertight and m.body_count == 1 and
          abs(m.volume - vol_expect) / vol_expect < 0.10,
          f"watertight {m.is_watertight}, bodies {m.body_count}, "
          f"vol {m.volume:.0f} vs {vol_expect:.0f} mm^3")

    inside_solid, cs = classify(segs, (0.0, 12.0))
    check("N1 classifier control", inside_solid and inside_solid != inside_hole,
          f"solid pt crossings {cs} (odd=inside) vs hole pt {ch}")

    allp = all(ok for _, ok, _ in results)
    for name, ok, detail in results:
        print(f"{'PASS' if ok else 'FAIL'}  {name}: {detail}")
    print("ALL_PASS" if allp else "CONTRACT_FAIL")
    if allp:
        out = OUT / "brim016_tophat_token.stl"
        m.export(out)
        print(f"wrote {out}  ({m.volume/1000:.2f} cm^3, "
              f"{len(m.faces)} faces)")

if __name__ == "__main__":
    main()
