"""Load CadQuery with only the VTK modules its OCC adapters need."""
from math import isfinite
import sys
from threading import RLock
from types import ModuleType

_lock=RLock()


def load():
    with _lock:
        if 'cadquery' in sys.modules:
            return sys.modules['cadquery']
        # OCP's IVtk adapters use `import vtk` as a presence check. CadQuery
        # uses the concrete vtkmodules API. Avoid VTK's import-all façade.
        from vtkmodules.vtkCommonCore import vtkObject
        marker=ModuleType('vtk')
        marker.vtkObject=vtkObject
        sys.modules.setdefault('vtk',marker)
        try:
            import cadquery
            return cadquery
        finally:
            if sys.modules.get('vtk') is marker:sys.modules.pop('vtk')


def volume(shape):
    """Reuse the default B-Rep integral for a shape used in several checks."""
    try:
        return shape._boltstudio_volume
    except AttributeError:
        value = shape.Volume()
        shape._boltstudio_volume = value
        return value


def has_positive_volume(shape):
    # The quick integral only decides the sign for well-resolved volumes.
    # Small or ambiguous results use the same integral as the dimensional checks.
    if hasattr(shape, '_boltstudio_volume'):
        value = volume(shape)
        return isfinite(value) and value > 0
    try:
        estimate = shape.Volume(.002)
        if isfinite(estimate) and estimate > 1e-4:
            return True
    except RuntimeError:
        pass
    value = volume(shape)
    return isfinite(value) and value > 0


def _volume_estimate(shape):
    """Fast adaptive integration and a guard band for near-limit decisions."""
    if hasattr(shape, '_boltstudio_volume'):
        return volume(shape), 0.

    try:
        return shape._boltstudio_volume_estimate
    except AttributeError:
        pass
    from OCP.BRepGProp import BRepGProp
    from OCP.GProp import GProp_GProps

    props = GProp_GProps()
    try:
        error = BRepGProp.VolumeProperties_s(shape.wrapped, props, 1e-5)
        value = props.Mass()
        if isfinite(value) and isfinite(error) and error >= 0:
            # The kernels use different quadratures. Allow for their observed
            # disagreement as well as the adaptive integration's error estimate.
            margin = max(1e-7, abs(value) * max(2e-4, 8 * error))
            shape._boltstudio_volume_estimate = (value, margin)
            return value, margin
    except RuntimeError:
        pass
    return volume(shape), 0.


def volume_change_between(before, after, minimum, maximum=float('inf')):
    """Use the original integral whenever an estimate is near either limit."""
    initial, initial_margin = _volume_estimate(before)
    final, final_margin = _volume_estimate(after)
    change = final - initial
    margin = initial_margin + final_margin
    if minimum + margin < change < maximum - margin:
        return True
    # Retry even apparently out-of-range estimates to preserve the recovery
    # behavior near a failed Boolean or a poorly conditioned spline.
    return minimum < volume(after) - volume(before) < maximum
