#!/usr/bin/env python3
"""Render simple isometric previews of the exported STL parts.

The renderer is intentionally dependency-light: it reads ASCII STL triangles,
projects them orthographically and paints them back-to-front with a single
directional light.  It is meant for documentation, not for visual inspection
of fine features.

    python3 render_stl.py
"""

from __future__ import annotations

import math
import os

from PIL import Image, ImageDraw, ImageFont

HERE = os.path.dirname(os.path.abspath(__file__))
STL = os.path.join(HERE, "..", "stl")
OUT = os.path.join(HERE, "..", "preview")
os.makedirs(OUT, exist_ok=True)

YAW = math.radians(28.0)
PITCH = math.radians(18.0)
LIGHT = (0.38, 0.62, 0.68)
SIZE = 900
SS = 2  # supersampling factor

COLORS = {
    "face": (232, 230, 224),
    "back": (198, 200, 202),
    "tray": (92, 132, 178),
    "pipe": (228, 186, 78),
    "pcb": (42, 122, 72),
    "devkit": (32, 78, 52),
    "oled": (24, 24, 27),
    "cell": (226, 138, 90),
    "hub": (198, 176, 138),
    "canbank": (166, 120, 172),
}


def load_stl(path: str) -> list[tuple[tuple[float, float, float], ...]]:
    tris = []
    loop: list[tuple[float, float, float]] = []
    with open(path, encoding="ascii", errors="ignore") as fh:
        for line in fh:
            s = line.strip()
            if s.startswith("vertex"):
                _, x, y, z = s.split()
                loop.append((float(x), float(y), float(z)))
                if len(loop) == 3:
                    tris.append(tuple(loop))
                    loop = []
    return tris


def rotate(tris, rx=0.0, ry=0.0, rz=0.0):
    cx, sx = math.cos(math.radians(rx)), math.sin(math.radians(rx))
    cy, sy = math.cos(math.radians(ry)), math.sin(math.radians(ry))
    cz, sz = math.cos(math.radians(rz)), math.sin(math.radians(rz))
    out = []
    for a, b, c in tris:
        vs = []
        for x, y, z in (a, b, c):
            # X
            y, z = y * cx - z * sx, y * sx + z * cx
            # Y
            x, z = x * cy + z * sy, -x * sy + z * cy
            # Z
            x, y = x * cz - y * sz, x * sz + y * cz
            vs.append((x, y, z))
        out.append(tuple(vs))
    return out


def translate(tris, dx=0.0, dy=0.0, dz=0.0):
    return [tuple((x + dx, y + dy, z + dz) for x, y, z in tri) for tri in tris]


def box(x0, y0, z0, x1, y1, z1):
    """Return the 12 triangles of an axis-aligned box."""
    p = [
        (x0, y0, z0), (x1, y0, z0), (x1, y1, z0), (x0, y1, z0),
        (x0, y0, z1), (x1, y0, z1), (x1, y1, z1), (x0, y1, z1),
    ]
    faces = [
        (0, 3, 2, 1), (4, 5, 6, 7), (0, 1, 5, 4),
        (1, 2, 6, 5), (2, 3, 7, 6), (3, 0, 4, 7),
    ]
    tris = []
    for a, b, c, d in faces:
        tris.append((p[a], p[b], p[c]))
        tris.append((p[a], p[c], p[d]))
    return tris


def color_for(name: str, base):
    return base


def render(parts, out_name, yaw=YAW, pitch=PITCH, title="", note=""):
    # parts = list of (name, triangles)
    all_tris = []
    for name, tris in parts:
        base = COLORS[name]
        for tri in tris:
            all_tris.append((name, base, tri))

    # Project every vertex (yaw about Y, pitch about X, orthographic).
    cy, sy = math.cos(yaw), math.sin(yaw)
    cp, sp = math.cos(pitch), math.sin(pitch)

    def proj(p):
        x, y, z = p
        x1 = x * cy + z * sy
        z1 = -x * sy + z * cy
        y2 = y * cp - z1 * sp
        z2 = y * sp + z1 * cp
        return x1, -y2, z2  # screen y is down

    pts = [proj(v) for _, _, tri in all_tris for v in tri]
    xs = [p[0] for p in pts]
    ys = [p[1] for p in pts]
    w = max(xs) - min(xs)
    h = max(ys) - min(ys)
    margin = 40.0
    scale = (SIZE * SS - 2 * margin) / max(w, h)
    ox = (SIZE * SS - w * scale) / 2 - min(xs) * scale
    oy = (SIZE * SS - h * scale) / 2 - min(ys) * scale

    img = Image.new("RGB", (SIZE * SS, SIZE * SS), (248, 248, 246))
    draw = ImageDraw.Draw(img)

    lx, ly, lz = LIGHT
    ln = math.sqrt(lx * lx + ly * ly + lz * lz)
    lx, ly, lz = lx / ln, ly / ln, lz / ln

    def shade(base, tri):
        (ax, ay, az), (bx, by, bz), (cx, cy2, cz) = tri
        ux, uy, uz = bx - ax, by - ay, bz - az
        vx, vy, vz = cx - ax, cy2 - ay, cz - az
        nx = uy * vz - uz * vy
        ny = uz * vx - ux * vz
        nz = ux * vy - uy * vx
        nn = math.sqrt(nx * nx + ny * ny + nz * nz) or 1.0
        d = abs((nx * lx + ny * ly + nz * lz) / nn)
        k = 0.34 + 0.66 * d
        return tuple(max(0, min(255, int(c * k))) for c in base)

    # Painter's algorithm: far triangles first.
    order = []
    for name, base, tri in all_tris:
        d = sum(proj(v)[2] for v in tri) / 3.0
        order.append((d, name, base, tri))
    order.sort(key=lambda t: t[0])

    for _, name, base, tri in order:
        poly = []
        for v in tri:
            sx, sy2, _ = proj(v)
            poly.append((ox + sx * scale, oy + sy2 * scale))
        draw.polygon(poly, fill=shade(base, tri))

    img = img.resize((SIZE, SIZE), Image.LANCZOS)
    draw = ImageDraw.Draw(img)
    try:
        font = ImageFont.truetype(
            "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 22)
        small = ImageFont.truetype(
            "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 16)
    except OSError:
        font = ImageFont.load_default()
        small = font
    draw.text((28, 22), title, fill=(35, 35, 35), font=font)
    if note:
        draw.text((28, SIZE - 32), note, fill=(90, 90, 90), font=small)
    path = os.path.join(OUT, out_name)
    img.save(path)
    print("wrote", path)


def main():
    face = load_stl(os.path.join(STL, "patress_3x6_face.stl"))
    back = load_stl(os.path.join(STL, "patress_3x6_back.stl"))
    tray = load_stl(os.path.join(STL, "patress_3x6_tray.stl"))
    pipe = load_stl(os.path.join(STL, "patress_3x6_pipe.stl"))

    render([("face", face)], "preview_face.png",
           title="3x6 faceplate - 146 x 86 x 23.5 mm",
           note="OLED window, LED hole and four wall-screw countersinks")
    render([("back", back)], "preview_back.png",
           title="Recessed can - 136 x 76 x 34 mm",
           note="open toward the faceplate; glands and vents in the shell")
    render([("tray", tray)], "preview_tray.png",
           title="DevKit clip tray - 46 x 65.4 x 5.7 mm",
           note="pin slots, USB relief and two M3 ears")
    render([("pipe", pipe)], "preview_pipe.png", yaw=math.radians(35),
           title="Light pipe - 5.5 x 5.5 x 21.5 mm",
           note="flange on the faceplate, rounded tip at the PCB LED")

    # ---- Rev A v3: expandable universal relay holder --------------------
    cell = load_stl(os.path.join(STL, "patress_3x6_relay_cell.stl"))
    hub = load_stl(os.path.join(STL, "patress_3x6_relay_hub.stl"))
    canbank = load_stl(os.path.join(STL, "patress_3x6_relay_canbank.stl"))

    render([("cell", cell)], "preview_relay_cell.png", yaw=math.radians(30),
           title="Relay bay cell (chainable) - 53.5 x 78.8 x 13.2 mm",
           note="open bay + solder combs both ends; dovetail keys on +X for chaining")

    render([("hub", hub)], "preview_relay_hub.png", yaw=math.radians(28),
           pitch=math.radians(14),
           title="Relay hub, room-side - 224.8 x 102.8 mm (4 cells)",
           note="masonry-anchor plate: socket for any chainable relay cell, extend at will")

    render([("canbank", canbank)], "preview_relay_canbank.png", yaw=math.radians(30),
           title="In-can 2-cell bank - 100.4 x 70.8 mm (deep can)",
           note="sits under the PCB on can-floor screws; comb strips narrow for the 71.2 pocket")

    # Assembly: faceplate, can, carrier, DevKit, OLED and light pipe.
    pcb = box(-65, -35, -23.6, 65, 35, -22)
    dev = box(-39.5, -22.85, -19.5, -11.65, 33.05, -17.9)
    oled = box(32 - 13, 21 - 7, -5.5, 32 + 13, 21 + 7, -4.0)
    pipe_placed = translate(rotate(pipe, rx=180), dx=1, dy=-9, dz=0)
    assembly = [
        ("back", back),
        ("pcb", pcb),
        ("tray", translate(tray, dz=-22)),
        ("devkit", dev),
        ("oled", oled),
        ("pipe", pipe_placed),
        ("face", face),
    ]
    render(assembly, "preview_assembly.png", yaw=math.radians(30),
           pitch=math.radians(20),
           title="Assembled enclosure - front view",
           note="the interior stack is shown in preview_exploded.png")

    # Exploded along Z to show the sandwich order.
    exploded = [
        ("back", translate(back, dz=-20)),
        ("pcb", translate(pcb, dz=0)),
        ("tray", translate(tray, dz=8)),
        ("devkit", translate(dev, dz=8)),
        ("oled", translate(oled, dz=15)),
        ("pipe", translate(pipe_placed, dz=15)),
        ("face", translate(face, dz=25)),
    ]
    render(exploded, "preview_exploded.png", yaw=math.radians(32),
           pitch=math.radians(22),
           title="Exploded assembly (not to scale along Z)",
           note="faceplate (front) / OLED / tray+DevKit / PCB / recessed can")


if __name__ == "__main__":
    main()
