#!/usr/bin/env python3
"""Export the enclosure and motor-mount parts as STL (and the motor plate and the backplate as SVG/DXF) for Tinkercad, and
check each mesh. The ring heat plate's DXF comes from tools/gen_ring_plate.py (from the ring board); the model imports it.

  python enclosure/export_stl.py

Needs OpenSCAD (2021.01 or newer) on the PATH or in C:/Program Files/OpenSCAD. Writes enclosure/tinkercad/*.stl.
Each STL is checked: every edge must be shared by exactly two triangles (a closed mesh), and the bounding box, volume
and triangle count are printed so they can be compared with the table in MOTOR_MOUNT.md.
"""
import glob
import os
import re
import shutil
import struct
import subprocess
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
OUT = os.path.join(HERE, "tinkercad")

LAYOUT_PARTS = ["case", "lid", "tray", "motor", "balls", "blocks", "backplate", "io_connectors", "platter", "knobs", "fan", "psu", "pcb", "cutaway"]
MOUNT_PARTS = [("motor_plate", "plate"), ("motor_standoff", "standoff"), ("motor_nema17", "motor")]


def openscad():
    exe = shutil.which("openscad") or shutil.which("openscad.com")
    if exe:
        return exe
    hits = glob.glob("C:/Program Files/OpenSCAD*/openscad.com")
    if hits:
        return hits[0]
    sys.exit("OpenSCAD not found")


def run(args):
    r = subprocess.run([openscad()] + args, capture_output=True, text=True)
    if r.returncode != 0:
        sys.exit(r.stderr)


def read_stl(path):
    data = open(path, "rb").read()
    if data[:5] == b"solid" and b"facet" in data[:400]:
        v = [tuple(map(float, m)) for m in re.findall(rb"vertex\s+(\S+)\s+(\S+)\s+(\S+)", data)]
        return [v[i:i + 3] for i in range(0, len(v), 3)]
    n = struct.unpack_from("<I", data, 80)[0]
    tris = []
    for i in range(n):
        f = struct.unpack_from("<12fH", data, 84 + i * 50)
        tris.append([f[3:6], f[6:9], f[9:12]])
    return tris


def check(path):
    tris = read_stl(path)
    edges = {}
    vol = 0.0
    lo = [1e18] * 3
    hi = [-1e18] * 3

    def key(p):
        return (round(p[0], 4), round(p[1], 4), round(p[2], 4))
    for a, b, c in tris:
        for p in (a, b, c):
            for k in range(3):
                lo[k] = min(lo[k], p[k]); hi[k] = max(hi[k], p[k])
        vol += (a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0])) / 6.0
        for p, q in ((a, b), (b, c), (c, a)):
            e = (key(p), key(q))
            edges[e] = edges.get(e, 0) + 1
    bad = sum(1 for (p, q), n in edges.items() if edges.get((q, p), 0) != n)
    return len(tris), lo, hi, vol, bad


def main():
    os.makedirs(OUT, exist_ok=True)
    jobs = []
    for p in LAYOUT_PARTS:
        jobs.append((f"enclosure_{p}", os.path.join(HERE, "layout.scad"), ["-D", f'part="{p}"']))
    for name, mode in MOUNT_PARTS:
        jobs.append((name, os.path.join(HERE, "motor_mount.scad"), ["-D", f'mode="{mode}"']))
    ok = True
    for name, src, defs in jobs:
        out = os.path.join(OUT, name + ".stl")
        run(["-o", out] + defs + [src])
        n, lo, hi, vol, bad = check(out)
        size = [hi[i] - lo[i] for i in range(3)]
        print(f"{name:20s} {n:6d} tris  min ({lo[0]:7.1f},{lo[1]:7.1f},{lo[2]:7.1f})  size ({size[0]:6.1f} x {size[1]:6.1f} x {size[2]:6.1f})  "
              f"volume {vol/1000:9.1f} cm3  {'CLOSED' if bad == 0 else 'OPEN EDGES: ' + str(bad)}  {os.path.getsize(out)//1024} KB")
        ok &= bad == 0
    for path in (os.path.join(OUT, "motor_plate.svg"), os.path.join(HERE, "motor_plate.dxf")):
        run(["-o", path, "-D", 'mode="plate2d"', os.path.join(HERE, "motor_mount.scad")])
    print("plate outline written as tinkercad/motor_plate.svg and motor_plate.dxf")
    for path in (os.path.join(OUT, "backplate.svg"), os.path.join(HERE, "backplate.dxf")):
        run(["-o", path, "-D", 'part="backplate2d"', os.path.join(HERE, "layout.scad")])
    print("backplate (seen from outside) written as tinkercad/backplate.svg and backplate.dxf")
    old = os.path.join(OUT, "enclosure_io_plate.stl")   # the I/O plate became the full-width backplate
    if os.path.exists(old):
        os.remove(old)
    sys.exit(0 if ok else 1)


if __name__ == "__main__":
    main()
