import os
import pathlib
import platform
import shutil
import sys


# On Windows prepend the path to our dlls to the PATH environment variable.
# Otherwise our dlls won't be found when our Python extensions are loaded
# by Python.
if sys.platform == "win32":
    pcraster_app_path = shutil.which("pcrcalc.exe")
    if pcraster_app_path:
        pcraster_bin_pathname = pathlib.Path(pcraster_app_path).parent.absolute()
        os.add_dll_directory(pcraster_bin_pathname)


# Check if we can import our compiled module
try:
    from ._pcraster import *
except ImportError as error:
    # Test matching Python versions
    major, minor, patchlevel = platform.python_version_tuple()
    python_version = (int(major), int(minor))
    build_version = (3, 13)

    # Major and minor should match
    if build_version != python_version:
        msg = f"The 'pcraster' module was built for Python 3.13, the version used is {major}.{minor}"
        raise ImportError(msg)

    # Test matching bitness
    nr_bits = 64 if sys.maxsize > 2**32 else 32

    if nr_bits != 64:
        msg = f"The 'pcraster' module was built for 64-bit, the Python version used is {nr_bits}-bit"
        raise ImportError(msg)

    # No support for Python 2
    if major == 2:
        msg = "The 'pcraster' module was built for Python 3.13, Python 2 is unsupported"
        raise ImportError(msg)

    msg = ""

    # VS2017 and runtime components related issues
    if sys.platform == "win32":
        if build_version != python_version:
            msg += "The 'pcraster' module was built for Python 3.13, the version used is {}.{}".format(
                major, minor)
            raise ImportError(msg)

        msg += "The 'Microsoft Visual C++ Redistributable for Visual Studio 2017' is required to run PCRaster, available at:\n"
        msg += "https://support.microsoft.com/en-us/help/2977003/the-latest-supported-visual-c-downloads\n"

    # Something else went wrong...
    msg += "{}\n".format(error)
    msg += "In case you cannot solve the issue please consult the PCRaster mailing list at:\nhttps://lists.geo.uu.nl/mailman/listinfo/pcraster-info\n"
    raise ImportError(msg)
except Exception as error:
    raise error


# If importing the compiled module succeeds everything else should be fine as well
from .operations import *
from . import operators
from .aguila import *
from .numpy_operations import *
from .__about__ import (
    __version__, __author__, __uri__, __license__, __copyright__
)

try:
    from ._pcraster_modflow import *
except ImportError:
    pass  # Modflow module was not installed

try:
    _var = "PCRASTER_NR_WORKER_THREADS"
    _workers = int(os.environ[_var])
    from .multicore import *
    set_nr_worker_threads(_workers)
except ValueError as err:
    msg = "Could not obtain the number of worker threads. The environment variable {} is set to '{}'; use an integer value instead.".format(
        _var, os.environ[_var])
    raise RuntimeError(msg)
except KeyError:
    pass  # No multicore module use intended
except ImportError:
    pass  # Multicore module was not installed


try:
    import matplotlib
    from .matplotlib import plot

except ImportError as e:
    pass  # Matplotlib module was not installed
