"""
This module imports the right Qt bindings, which are compatible
with the version of the Qt framework OVITO has been built against.
"""

import os

# Import Shiboken module first to preload shiboken6.dll, which is needed by the Qt DLLs.
import shiboken6 as shiboken

# Try to tell other 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'

# PySide6 submodules are imported lazily via module-level __getattr__ rather than at import time.
# Importing PySide6.QtGui (and other Qt modules that load platform plugins) fails on headless
# Linux systems that lack the XCB system packages. Deferring the import ensures that simply
# doing `import ovito.qt_compat` never triggers that failure; the error only surfaces when
# the caller explicitly requests a specific Qt submodule.
_QT_SUBMODULES = {'QtCore', 'QtGui', 'QtWidgets', 'QtNetwork', 'QtXml'}

def __getattr__(name):
    if name not in _QT_SUBMODULES:
        raise AttributeError(f"module 'ovito.qt_compat' has no attribute {name!r}")
    from importlib import import_module
    module = import_module(f'PySide6.{name}')
    if name == 'QtCore':
        # Map DeprecationWarning methods
        module.QCoreApplication.exec_ = module.QCoreApplication.exec
        module.QEventLoop.exec_ = module.QEventLoop.exec
        module.QThread.exec_ = module.QThread.exec
    globals()[name] = module
    return module
