"""Fit checks for the rail/latch, the GoPro joint, the USER plunger and the privacy cap."""
import coral_eye as ce
import accessories as ac
from build123d import Pos, Rot, import_step
import os


def vol(a, b):
    i = a & b
    return i.volume if i else 0.0


body = ce.make_body()
parts = ac.all_parts()
play_z = ac.T_CLEAR                       # how far a mount can drop back in the dovetail
print("== rail + latch (worst case: mount pushed back by the full play of %.2f mm)" % play_z)
for name in ("CoralEye_Mount_GoPro", "CoralEye_Mount_Tripod"):
    p = parts[name]
    seated = vol(body, p)
    row = []
    for dy in (-0.6, -1.5, -3.0, -8.0):
        row.append(vol(body, Pos(0, dy, -play_z) * p))
    print(f"{name:24s} seated overlap {seated:6.3f} mm3 | sliding (pushed back) overlaps "
          + ", ".join(f"{v:5.3f}" for v in row))
for name in ("CoralEye_Mount_Wall", "CoralEye_Mount_Magnet"):   # no latch: must slide freely all the way
    p = parts[name]
    row = [vol(body, Pos(0, dy, 0) * p) for dy in (0.0, -3.0, -10.0, -20.0)]
    print(f"{name:24s} (no latch) overlaps seated/sliding " + ", ".join(f"{v:5.3f}" for v in row))

st, ad = parts["CoralEye_Stand"], parts["CoralEye_Mount_GoPro"]
print("== GoPro joint: stand vs adapter %.3f mm3" % vol(st, ad))
for ang in (-35, -20, 20, 45):
    rot = Pos(0, ac.AXIS_Y, ac.AXIS_Z) * Rot(ang, 0, 0) * Pos(0, -ac.AXIS_Y, -ac.AXIS_Z)
    print("   tilt %+d deg -> camera+adapter vs stand %.3f mm3" % (ang, vol(st, rot * (body + ad))))

pl = ce.make_user_plunger()
print("== USER plunger vs body %.3f mm3" % vol(pl, body))
step = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..",
                                     "referencia-oficial", "Synaptics_CoralBoard_SL.step"))
board = import_step(step)
near = [s for s in board.solids() if s.bounding_box().min.Y < -1.0 and s.bounding_box().min.X < 12]
print("   plunger vs board parts near the USER button: %.3f mm3" % sum(vol(pl, s) for s in near))
print("   plunger pushed 0.4 mm in -> touches the stem: %.3f mm3" % sum(vol(Pos(0, 0.4, 0) * pl, s) for s in near))
