import unittest

import numpy as np
from OCP.BRep import BRep_Builder
from OCP.BRepPrimAPI import BRepPrimAPI_MakeCylinder
from OCP.TopoDS import TopoDS_Compound
from OCP.gp import gp_Ax2, gp_Dir, gp_Pnt

from exterior import DIRECTIONS, ShellError, TopAbs_FACE, generate, members, read_step
from OCP.BRepAdaptor import BRepAdaptor_Surface
from OCP.GeomAbs import GeomAbs_Cylinder
from OCP.TopoDS import TopoDS


def assembly():
    frame = gp_Ax2(gp_Pnt(0, 0, 0), gp_Dir(0, 1, 0))
    stock = BRepPrimAPI_MakeCylinder(frame, 32.5, 9.2).Solid()
    frame = gp_Ax2(gp_Pnt(0, 9.0, 0), gp_Dir(0, 1, 0))
    pin = BRepPrimAPI_MakeCylinder(frame, 2, 9).Solid()
    bundle, build = TopoDS_Compound(), BRep_Builder()
    build.MakeCompound(bundle)
    build.Add(bundle, stock)
    build.Add(bundle, pin)
    return bundle


class OpeningTests(unittest.TestCase):
    def test_every_signed_direction(self):
        source = assembly()
        for direction, normal in DIRECTIONS.items():
            with self.subTest(direction=direction):
                result = generate(source, end=direction)
                self.assertEqual(result.opening.label, direction)
                np.testing.assert_allclose(result.opening.normal, normal)
                self.assertTrue(result.step("shell") and result.step("surface"))

    def test_exposed_boss_keeps_offset_radius(self):
        result = generate(assembly(), end="-Y")
        surfaces = [BRepAdaptor_Surface(TopoDS.Face_s(item))
                    for item in members(read_step(result.step("surface")), TopAbs_FACE)]
        radii = [face.Cylinder().Radius() for face in surfaces if face.GetType() == GeomAbs_Cylinder]
        for expected in (2.5, 33.):
            self.assertTrue(any(abs(radius-expected) < 1e-6 for radius in radii))

    def test_custom_direction_and_opening_shift(self):
        result = generate(assembly(), end="1,1,0", depth=4)
        np.testing.assert_allclose(result.opening.normal, np.array((1,1,0))/np.sqrt(2))
        self.assertAlmostEqual(result.opening.height, (32.5+9.2)/np.sqrt(2)-4)

    def test_zero_clearance_side_can_open_with_positive_depth(self):
        self.assertTrue(generate(assembly(), gap=0, end="-X", depth=4).step("surface"))

    def test_invalid_direction_and_depth(self):
        with self.assertRaisesRegex(ShellError, "非零"):
            generate(assembly(), end="0,0,0")
        with self.assertRaisesRegex(ShellError, "内移过大"):
            generate(assembly(), end="+Y", depth=18)


if __name__ == "__main__":
    unittest.main()
