#
# Copyright 2017-2018 Ettus Research, a National Instruments Company
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
"""UHD Python API module."""

import os

# As of python3.8, python stopped using PATH to search for DLLs on Windows, and
# required the use of os.add_dll_directory to add paths to the DLL search.
if os.name == "nt":
    uhd_dll_name = "uhd.dll"
    uhd_dll_dir = None
    if hasattr(os, "add_dll_directory"):
        # First, check for a user defined path to the UHD libraries.
        # This might be the case for files built from source but not installed yet.
        uhd_dll_dir = os.environ.get("UHD_LIBRARY_PATH")
        if not uhd_dll_dir or not os.path.exists(os.path.join(uhd_dll_dir, uhd_dll_name)):
            # The UHD_PKG_PATH will be set if UHD was installed with a UHD NSIS installer,
            # use this path to find the uhd.dll and add it to the DLL search.
            uhd_pkg_dir = os.environ.get("UHD_PKG_PATH")
            if uhd_pkg_dir is not None and os.path.exists(
                os.path.join(uhd_pkg_dir, "bin", uhd_dll_name)
            ):
                uhd_dll_dir = os.path.join(uhd_pkg_dir, "bin")
            else:
                # If UHD_PKG_PATH is not set, the UHD may have been built and installed from source.
                # CMake will generate the UHD_INSTALL_PATH variable in the config_vars.py file using the
                # CMAKE_INSTALL_PREFIX, try to find the uhd.dll with this path.
                UHD_INSTALL_PATH = "/usr/pkg"
                if os.path.exists(os.path.join(UHD_INSTALL_PATH, "bin", uhd_dll_name)):
                    uhd_dll_dir = os.path.join(UHD_INSTALL_PATH, "bin")
        # perform version check if uhd.dll path was found
        if uhd_dll_dir:
            # compare version of uhd.dll against the version used for the cmake build process
            # potentially this could be a different version, if the NSIS installer did perform
            # an upgrade of uhd.dll separately
            UHD_VERSION = "4.9.0.0-0-unknown"
            from .utils.version_check import compare_versions, get_windll_version

            os.add_dll_directory(uhd_dll_dir)
            uhd_dll_version = get_windll_version(os.path.join(uhd_dll_dir, uhd_dll_name))
            if compare_versions(uhd_dll_version, UHD_VERSION) != 0:
                print(
                    f"WARNING: Version conflict between {uhd_dll_name}({uhd_dll_version}) and "
                    f"the Python API build version({UHD_VERSION})!\nIt is recommended to align "
                    "the UHD binary installation and the UHD Python module to the exact same version "
                    "by upgrading the older component."
                )
    if not uhd_dll_dir:
        print(
            f"WARNING: Failed to add {uhd_dll_name} path to DLL search, module may not import properly, "
            "version check skipped.\nPlease ensure UHD_PKG_DIR (binary installation) is set correctly. "
            'For Python version < 3.8 the "UHD\\bin" directory needs to be added to PATH environment variable.'
        )

try:
    from . import chdr, dsp, filters, rfnoc, types, usrp, usrp_clock, usrpctl
    from .libpyuhd import find, get_abi_string, get_component, get_version_string
    from .libpyuhd.paths import *  # noqa: F403
    from .property_tree import PropertyTree

    __version__ = get_version_string()
except ImportError as e:
    enable_pymod_utils = "ON"
    if enable_pymod_utils != "ON":
        raise e

    def get_tmp_path():
        """Return the path to the temporary directory (Python-only version)."""
        env_path = os.environ.get("UHD_TEMP_PATH")
        if env_path is not None and os.path.isdir(env_path):
            return env_path
        import tempfile

        return tempfile.gettempdir()

    def get_pkg_path():
        """Return the path to the UHD package directory (Python-only version)."""
        env_path = os.environ.get("UHD_PKG_PATH")
        if env_path is not None and os.path.isdir(env_path):
            return env_path
        return "/usr/pkg"

    def get_pkg_data_path():
        """Return the path to the UHD package directory (Python-only version)."""
        env_path = os.environ.get("UHD_PKG_DATA_PATH")
        if env_path is not None and os.path.isdir(env_path):
            return env_path
        return os.path.join("/usr/pkg", "share/uhd")

    __version__ = "4.9.0.0-0-unknown"
