import sys
import os

# This is the ovito.plugins Python package. It hosts the C++ extension modules of OVITO Pro.

# The C++ extension modules are, however, located in a different directory when OVITO Pro is installed
# as an application. For the time being, we use hardcoded, relative paths to find them.
#
# Platform-dependent paths where this Python module is located:
#   Linux:   lib/ovito/plugins/python/ovito/plugins/
#   Windows: plugins/python/ovito/plugins/
#   macOS:   Ovito.app/Contents/Resources/python/ovito/plugins/
#
# Platform-dependent paths where the native C++ shared libraries are located:
#   Linux:   lib/ovito/plugins/
#   Windows: .
#   macOS:   Ovito.app/Contents/PlugIns/

# Note: The following condition depends on the value of the CMake build option OVITO_BUILD_MONOLITHIC and gets resolved at build time.
if 'ON' == 'OFF':
    # If the OVITO plugins are present as shared libraries, we need to specify
    # the path where they are found:
    if sys.platform.startswith('darwin'):
        # macOS
        __path__.append(__path__[0] + "/../../../../PlugIns")
    elif sys.platform.startswith('win32'):
        # Windows
        __path__.append(__path__[0] + "\\..\\..\\..\\..")
    else:
        # Linux
        __path__.append(__path__[0] + "/../../..")

    # On Windows, C extension modules for the Python interpreter have a .pyd file suffix.
    # The OVITO plugins, however, use the standard .ovito.dll suffix. We therefore need to implement
    # a custom file entry finder and hook it into the import machinery of Python.
    # It specifically handles the OVITO plugin path and allows loading extension modules with .ovito.dll
    # extension instead of .pyd.
    if sys.platform.startswith('win32'):
        import importlib.machinery
        def OVITOPluginFinderHook(path):
            if path == __path__[-1]:
                return importlib.machinery.FileFinder(path, (importlib.machinery.ExtensionFileLoader, ['.ovito.dll']))
            raise ImportError()
        sys.path_hooks.insert(0, OVITOPluginFinderHook)
elif 'ON' == 'ON':
    # If all plugins were statically linked into the main OVITO executable,
    # make them loadable as built-in modules below the ovito.plugins package.
    import importlib.machinery
    def OVITOBuiltinPluginFinderHook(path):
        if path == __path__[-1]:
            return importlib.machinery.BuiltinImporter()
        raise ImportError()
    sys.path_hooks.insert(0, OVITOBuiltinPluginFinderHook)
else:
    assert(False) # CMake variable OVITO_BUILD_MONOLITHIC was set to neither ON nor OFF.

# Try to tell third-party Python modules (e.g. matplotlib) to use the same Qt bindings as OVITO.
# Typically, this is done through the environment variable QT_API.
if not 'QT_API' in os.environ:
    os.environ['QT_API'] = 'pyside6'
