"""Section meshes through the camera axis (render only): shows how the flex cable runs."""
import os
from build123d import Box, Pos, export_stl, Compound
import coral_eye as ce

M = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "render", "meshes"))


def keep_left(shape, x_cut):
    """Keep the part of `shape` with x <= x_cut."""
    half = Pos(x_cut - 150, 0, 0) * Box(300, 400, 400)
    return shape & half


if __name__ == "__main__":
    x_cut = ce.LENS_X
    tol = dict(tolerance=0.01, angular_tolerance=0.15)
    parts = {
        "cut_body": ce.make_body(),
        "cut_face": ce.make_face("skin"),
    }
    import shutter as sh
    for k, v in sh.assembly(0.0).items():
        parts["cut_" + k] = v
    pcb, lens, conn = ce.make_camera_mock()
    parts.update({"cut_campcb": pcb, "cut_lens": lens, "cut_camconn": conn})
    flex = ce.make_flex_cable()
    cable = flex[0]
    for p in flex[1:]:
        cable += p
    parts["cut_cable"] = cable
    for name, shp in parts.items():
        export_stl(keep_left(shp, x_cut), os.path.join(M, name + ".stl"), **tol)
        print("exported", name)
    # the board itself, cut solid by solid so the section is capped
    from build123d import import_step
    step = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..",
                                         "referencia-oficial", "Synaptics_CoralBoard_SL.step"))
    kept = []
    for s in import_step(step).solids():
        bb = s.bounding_box()
        if bb.min.X > x_cut:
            continue
        if bb.max.X <= x_cut:
            kept.append(s)
        else:
            try:
                c = keep_left(s, x_cut)
                if c is not None and c.volume > 1e-6:
                    kept.append(c)
            except Exception:  # noqa: BLE001 - a few tessellated solids refuse booleans; skip them
                pass
    export_stl(Compound(children=kept), os.path.join(M, "cut_board.stl"), tolerance=0.02, angular_tolerance=0.2)
    print("exported cut_board", len(kept))
