"""Tessellate independent CAD copies for display and mesh recovery."""
import numpy as np


class TessellationError(RuntimeError):
    pass


def face_triangles(shape, tolerance, angle, detail=False, min_size=0., *, parallel=True):
    from OCP.BRep import BRep_Tool
    from OCP.TopAbs import TopAbs_REVERSED
    from OCP.TopLoc import TopLoc_Location
    from OCP.BRepMesh import BRepMesh_IncrementalMesh
    from OCP.BRepTools import BRepTools
    from OCP.IMeshTools import IMeshTools_Parameters

    display = shape.copy(mesh=False)
    BRepTools.Clean_s(display.wrapped, True)
    settings = IMeshTools_Parameters()
    settings.Deflection = settings.DeflectionInterior = tolerance
    settings.Angle = settings.AngleInterior = angle
    settings.Relative = False
    settings.InParallel = parallel
    if min_size:
        settings.MinSize = min_size
    if hasattr(settings, 'EnableControlSurfaceDeflectionAllSurfaces'):
        settings.EnableControlSurfaceDeflectionAllSurfaces = detail

    mesher = BRepMesh_IncrementalMesh(display.wrapped, settings)
    flags = mesher.GetStatusFlags()
    if not mesher.IsDone():
        raise TessellationError(f'CAD 三角化失败（OCCT 状态 {flags}）')

    faces = display.Faces()
    if not faces:
        raise TessellationError('CAD 三角化失败（未找到曲面）')
    missing = []
    for index, face in enumerate(faces, 1):
        location = TopLoc_Location()
        poly = BRep_Tool.Triangulation_s(face.wrapped, location)
        if poly is None or not poly.NbTriangles():
            missing.append(f'{index}/{len(faces)} {face.geomType()}')
            continue
        count = poly.NbNodes()
        transform = None if location.IsIdentity() else location.Transformation()

        def coordinates():
            for i in range(1, count + 1):
                point = poly.Node(i)
                if transform is not None:
                    point = point.Transformed(transform)
                yield point.X()
                yield point.Y()
                yield point.Z()

        xyz = np.fromiter(coordinates(), count=3 * count, dtype=np.float64).reshape(-1, 3)
        cells = np.asarray([poly.Triangle(i).Get() for i in range(1, poly.NbTriangles() + 1)], dtype=np.int64)
        if face.wrapped.Orientation() == TopAbs_REVERSED:
            cells = cells[:, [0, 2, 1]]
        yield face, xyz, cells - 1

    if missing:
        sample = '、'.join(missing[:6])
        raise TessellationError(f'CAD 实体有 {len(missing)} 个曲面未三角化（{sample}；OCCT 状态 {flags}）')


def surface_normals(face):
    from OCP.BRep import BRep_Tool
    from OCP.BRepLib import BRepLib_ToolTriangulatedShape
    from OCP.TopAbs import TopAbs_REVERSED
    from OCP.TopLoc import TopLoc_Location

    location = TopLoc_Location()
    poly = BRep_Tool.Triangulation_s(face.wrapped, location)
    BRepLib_ToolTriangulatedShape.ComputeNormals_s(face.wrapped, poly)
    transform = None if location.IsIdentity() else location.Transformation()
    sign = -1 if face.wrapped.Orientation() == TopAbs_REVERSED else 1

    def components():
        for i in range(1, poly.NbNodes() + 1):
            normal = poly.Normal(i)
            if transform is not None:
                normal = normal.Transformed(transform)
            yield sign * normal.X()
            yield sign * normal.Y()
            yield sign * normal.Z()

    return np.fromiter(components(), count=3 * poly.NbNodes(), dtype=np.float32).reshape(-1, 3)


def triangulate(shapes, pitch, detail=False, log=None, *, cache=None):
    tolerance = max(.0015, min(.009, .006 * pitch)) if detail else max(.003, min(.035, .018 * pitch))
    angle = .12 if detail else .20
    min_size = 0. if detail else .035 * pitch
    # Retry on a fresh CAD copy if the initial tessellation fails.
    attempts = (
        (tolerance, angle, detail, min_size, True),
        (tolerance, angle, False, 0., False),
        (tolerance / 2, min(angle, .14), False, 0., False),
    )
    meshes = {}
    for name, shape in zip(('bolt', 'nut', 'washer', 'spring_washer'), shapes):
        if shape is None:
            continue
        previous = cache.get(name) if cache is not None else None
        cached_levels = previous[2] if previous and previous[0] is shape and previous[1] == pitch else {}
        if detail in cached_levels:
            meshes[name] = cached_levels[detail]
            continue
        reasons = []
        for tol, ang, control_surfaces, minimum, parallel in attempts:
            vertices, triangles, normals = [], [], []
            offset = 0
            try:
                for face, xyz, faces in face_triangles(shape, tol, ang, control_surfaces, minimum, parallel=parallel):
                    vertices.append(xyz.astype(np.float32))
                    triangles.append(faces + offset)
                    normals.append(surface_normals(face))
                    offset += len(xyz)
            except (RuntimeError, ValueError) as exc:
                reasons.append(str(exc))
                if log is not None and len(reasons) < len(attempts):
                    log(f'{name} 预览三角化重试。{exc}')
                continue
            meshes[name] = np.concatenate(vertices), np.concatenate(triangles), np.concatenate(normals)
            if cache is not None:
                cached_levels[detail] = meshes[name]
                cache[name] = (shape, pitch, cached_levels)
            if reasons and log is not None:
                log(f'{name} 预览三角化重试成功。')
            break
        else:
            raise TessellationError(f'[{name}] 预览三角化失败\n' + '\n'.join(reasons))
    return meshes
