#!/usr/bin/env python3
"""
Parametric generator for the Sonos Beam (Gen 2) under-TV hanger: two flat brackets (left and
right), the STLs in print orientation, preview PNGs and a dimensioned elevation SVG (mm).

Each bracket is a 5 mm strap that hangs from one of the TV's two bottom VESA screws (through a
short slot, so the height can be trimmed on the wall), runs straight down, slants inward and ends
in a foot behind the Beam and a shelf under it. A #10-32 screw goes up through the shelf into the
Beam's bottom threaded insert (6 in apart); the shelf carries the weight, a gusset stiffens it.

Bought parts / things to MEASURE (all marked "measure" below were not found in a spec sheet):
  * LG B6E 55 in (OLED55B6): VESA 300 x 200, M6.  Bottom row = the two 300 mm-apart holes.
  * Sonos Beam Gen 2: 651 x 100 x 68 mm; two threaded inserts in the bottom, 6 in apart.
Hardware: 2x #10-32 x 1/2 in pan-head screws (Beam side), 2x M6 screws long enough for the
original length + 5 mm (TV side; reuse the wall-mount screws if they are long enough).

Requirements:  pip install manifold3d trimesh numpy matplotlib
Usage:         python3 generate_beam_mount.py
"""
import os
import numpy as np
import trimesh
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 = 96

# -- TV (LG B6E 55 in) ------------------------------------------------------------------------
VESA_W = 300.0          # bottom VESA holes, centre to centre (stated: 300 x 200)
VESA_ABOVE_EDGE = 152.4  # bottom VESA row to the TV's bottom edge (stated: 6 in, measured)
M6_CLEAR = 6.6          # M6 clearance
SLOT_TRAVEL = 24.0      # slot length beyond the hole diameter: +-12 mm of height trim

# -- Beam (Gen 2) -----------------------------------------------------------------------------
BEAM_W, BEAM_D, BEAM_H = 651.0, 100.0, 68.0   # stated
BEAM_HOLE_DX = 6 * 25.4   # rear inserts, centre to centre (stated: 6 in)
BEAM_HOLE_FROM_BACK = 50.8  # inserts are in the BOTTOM; distance from the back face (stated: 2 in, measured)
SCREW_CLEAR = 5.0       # #10-32 clearance (0.19 in = 4.8, +0.2)
GAP_BELOW_TV = 25.0     # TV bottom edge to the top of the Beam (chosen; Sonos asks 25 mm above the Beam)

# -- bracket ----------------------------------------------------------------------------------
T = 5.0                 # strap thickness; Beam-side screw engages 12.7 - 5 = 7.7 mm
W = 28.0                # strap width
SLANT_START = 60.0      # strap stays vertical this far below the VESA hole (clears the wall-mount rail)
SHELF_T = 5.0           # shelf under the Beam; #10-32 x 1/2 bites 12.7 - 5 = 7.7 mm
GUSSET = 25.0           # gusset legs, under the shelf
GUSSET_T = 5.0

# -- derived ----------------------------------------------------------------------------------
X_TV = VESA_W / 2
X_BEAM = BEAM_HOLE_DX / 2
Z_BEAM_BOTTOM = VESA_ABOVE_EDGE + GAP_BELOW_TV + BEAM_H   # below the VESA hole: the shelf's top face
DROP = Z_BEAM_BOTTOM - BEAM_H / 2   # where the strap reaches the Beam's line (mid-height)


def capsule(p, q, r):
    return CrossSection.batch_hull([CrossSection.circle(r, SEG).translate(p),
                                    CrossSection.circle(r, SEG).translate(q)])


def right_bracket():
    """Right bracket, print orientation: x across, y = distance below the VESA hole, z up.

    Strap plate: z 0..T.  Shelf under the Beam: a fin standing up from the strap's foot (z 0..T+SHELF_D),
    y = Z_BEAM_BOTTOM..+SHELF_T, with the #10-32 hole through it.  One gusset under the shelf."""
    r = W / 2
    y_foot = Z_BEAM_BOTTOM + SHELF_T + GUSSET   # bottom of the pad, under the gussets
    body = (capsule((X_TV, -SLOT_TRAVEL / 2), (X_TV, SLANT_START), r)
            + capsule((X_TV, SLANT_START), (X_BEAM, DROP), r)
            + capsule((X_BEAM, DROP), (X_BEAM, y_foot - r), r))
    slot = capsule((X_TV, -SLOT_TRAVEL / 2), (X_TV, SLOT_TRAVEL / 2), M6_CLEAR / 2)
    plate = Manifold.extrude(body - slot, T)

    # shelf profile in (x, z): rectangle from the bed up to a rounded end, hole at BEAM_HOLE_FROM_BACK
    z_hole = T + BEAM_HOLE_FROM_BACK
    z_end = z_hole + r
    prof = (CrossSection.square((W, z_hole), center=False).translate((X_BEAM - r, 0))
            + CrossSection.circle(r, SEG).translate((X_BEAM, z_hole)))
    prof = prof - CrossSection.circle(SCREW_CLEAR / 2, SEG).translate((X_BEAM, z_hole))
    shelf = Manifold.extrude(prof, SHELF_T).rotate((90, 0, 0))       # (x, y, z) -> (x, -z, y)
    shelf = shelf.translate((0, Z_BEAM_BOTTOM + SHELF_T, 0))

    # gusset: right triangle in (y, z), under the shelf, against the strap, centred on the hole line
    tri = CrossSection([[(Z_BEAM_BOTTOM + SHELF_T, 0), (Z_BEAM_BOTTOM + SHELF_T + GUSSET, 0),
                         (Z_BEAM_BOTTOM + SHELF_T, GUSSET)]])
    return plate + shelf + gusset_from(tri)


def gusset_from(tri):
    """Extrude the (y, z) triangle along x and centre it on the hole line."""
    g = Manifold.extrude(tri, GUSSET_T)             # local (a, b, c) = (y, z, thickness)
    g = g.rotate((90, 0, 90))                       # a->y, b->z, c->x
    return g.translate((X_BEAM - GUSSET_T / 2, 0, 0))


def to_trimesh(man):
    m = man.to_mesh()
    return trimesh.Trimesh(np.asarray(m.vert_properties, float)[:, :3], np.asarray(m.tri_verts, int), process=True)


def render_preview(parts, name, elev=35, azim=-60, size=(5, 7)):
    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)
    los, his = [], []
    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); los.append(tm.bounds[0]); his.append(tm.bounds[1])
    lo, hi = np.min(los, axis=0), np.max(his, 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)); 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)


def elevation_svg(path):
    """Front elevation (as seen from behind the Beam), true scale 1 mm = 1 unit."""
    pad = 40
    xs0, xs1 = -BEAM_W / 2 - pad, BEAM_W / 2 + pad
    top = -(VESA_ABOVE_EDGE + 70)          # a bit of the TV above the VESA row
    bot = Z_BEAM_BOTTOM + SHELF_T + GUSSET + 40
    Wd, Ht = xs1 - xs0, bot - top
    right = right_bracket()
    # outline of the strap from a slice through the plate
    sl = right.slice(T / 2)
    def pts(poly):
        return " ".join(f"{x:.2f},{y:.2f}" for x, y in poly)
    def bracket(mirror):
        out = []
        for poly in sl.to_polygons():
            P = [(-x if mirror else x, y) for x, y in poly]
            out.append(f'<polygon class="pr" points="{pts(P)}" fill-rule="evenodd"/>')
        return "\n".join(out)
    s = []
    s.append(f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="{xs0:.0f} {top:.0f} {Wd:.0f} {Ht:.0f}" '
             f'width="{Wd:.0f}" height="{Ht:.0f}" font-family="sans-serif" font-size="9">')
    s.append("<style>.bg{fill:#fff}.tv{fill:#e7e7ea;stroke:#555;stroke-width:1}.beam{fill:#cfd3d8;stroke:#333;stroke-width:1}"
             ".pr{fill:#d9d2c3;stroke:#3a342a;stroke-width:1.2;stroke-linejoin:round}.dim{stroke:#a33;stroke-width:.7;fill:none}"
             ".t{fill:#222}.hole{fill:#fff;stroke:#333;stroke-width:.8}</style>")
    s.append(f'<rect class="bg" x="{xs0:.0f}" y="{top:.0f}" width="{Wd:.0f}" height="{Ht:.0f}"/>')
    s.append(f'<rect class="tv" x="{xs0:.0f}" y="{top:.0f}" width="{Wd:.0f}" height="{-top + VESA_ABOVE_EDGE:.0f}"/>')
    s.append(f'<text class="t" x="{xs0 + 6:.0f}" y="{top + 14:.0f}">LG B6E 55 in, seen from behind (TV bottom edge at y = {VESA_ABOVE_EDGE:.0f})</text>')
    s.append(f'<rect class="beam" x="{-BEAM_W / 2:.1f}" y="{Z_BEAM_BOTTOM - BEAM_H:.1f}" width="{BEAM_W}" height="{BEAM_H}" rx="12"/>')
    s.append(f'<text class="t" x="{-BEAM_W / 2 + 14:.0f}" y="{Z_BEAM_BOTTOM - BEAM_H / 2 + 3:.0f}">Sonos Beam (Gen 2) {BEAM_W:.0f} x {BEAM_H:.0f}</text>')
    s.append(bracket(False)); s.append(bracket(True))
    for sx in (-1, 1):
        s.append(f'<circle class="hole" cx="{sx * X_TV:.1f}" cy="0" r="{M6_CLEAR / 2}"/>')
    s.append(f'<line class="dim" x1="{-X_TV}" y1="-30" x2="{X_TV}" y2="-30"/><text class="t" x="0" y="-34" text-anchor="middle">VESA {VESA_W:.0f}</text>')
    yb = Z_BEAM_BOTTOM + SHELF_T + GUSSET + 25
    s.append(f'<line class="dim" x1="{-X_BEAM}" y1="{yb:.0f}" x2="{X_BEAM}" y2="{yb:.0f}"/><text class="t" x="0" y="{yb + 12:.0f}" text-anchor="middle">Beam bottom inserts {BEAM_HOLE_DX:.1f} (6 in), {BEAM_HOLE_FROM_BACK:.0f} from the back</text>')
    s.append(f'<line class="dim" x1="{X_TV + 45:.0f}" y1="0" x2="{X_TV + 45:.0f}" y2="{DROP:.1f}"/><text class="t" x="{X_TV + 50:.0f}" y="{DROP / 2:.0f}">VESA hole to Beam mid-height {DROP:.0f}</text>')
    s.append("</svg>")
    open(path, "w").write("\n".join(s))


def main():
    right = right_bracket()
    left = right.mirror((1, 0, 0))
    for name, man in (("beam_mount_right", right), ("beam_mount_left", left)):
        tm = to_trimesh(man)
        assert tm.is_watertight and tm.is_winding_consistent and tm.volume > 0, name
        tm.export(os.path.join(HERE, f"{name}.stl"))
        print(f"{name}: {tm.extents.round(1)} mm  {tm.volume / 1000:.1f} cm3  watertight={tm.is_watertight}")
        render_preview([(tm, (0.85, 0.8, 0.7))], name, elev=40, azim=115)
    # fit checks
    tm = to_trimesh(right)
    assert abs(2 * X_BEAM - 152.4) < 1e-6
    assert tm.bounds[1][1] >= Z_BEAM_BOTTOM + SHELF_T + GUSSET - 0.05   # foot reaches below the gusset
    assert BEAM_HOLE_FROM_BACK + W / 2 < BEAM_D + 10                      # shelf end stays under the Beam
    assert X_BEAM + W / 2 < BEAM_W / 2                          # pad is within the Beam's length
    assert X_TV - W / 2 > X_BEAM + W / 2 - 1                    # slant does not fold back across the pad
    elevation_svg(os.path.join(HERE, "beam-mount-elevation.svg"))
    print(f"VESA hole -> Beam mid-height = {DROP:.1f} mm; Beam top below the TV edge = {GAP_BELOW_TV} mm")


if __name__ == "__main__":
    main()
