#!python
"""
A generic wrapper to access nrn binaries from a python installation
Please create a softlink with the binary name to be called.
"""
import os
import platform
import shutil
import stat
import subprocess
import sys
import warnings
from importlib.metadata import metadata, PackageNotFoundError
from importlib.util import find_spec
from pathlib import Path

from setuptools.command.build_ext import new_compiler
from packaging.version import Version
from sysconfig import get_config_vars, get_config_var
from find_libpython import find_libpython


def _customize_compiler(compiler):
    """Do platform-specific customizations of compilers on unix platforms."""
    if compiler.compiler_type == "unix":
        (cc, cxx, cflags) = get_config_vars("CC", "CXX", "CFLAGS")
        if "CC" in os.environ:
            cc = os.environ["CC"]
        if "CXX" in os.environ:
            cxx = os.environ["CXX"]
        if "CFLAGS" in os.environ:
            cflags = cflags + " " + os.environ["CFLAGS"]
        cc_cmd = cc + " " + cflags
        # We update executables in compiler to take advantage of distutils arg splitting
        compiler.set_executables(compiler=cc_cmd, compiler_cxx=cxx)


def _set_default_compiler():
    """Set (dont overwrite) CC/CXX so that apps dont use the build-time ones"""
    ccompiler = new_compiler()
    _customize_compiler(ccompiler)
    # UnixCCompiler has .compiler / .compiler_cxx lists. MSVCCompiler does not.
    compiler = getattr(ccompiler, "compiler", None)
    compiler_cxx = getattr(ccompiler, "compiler_cxx", None)
    # xcrun wrapper must bring all args (Mac)
    if compiler and compiler[0] == "xcrun":
        ccompiler.compiler[0] = get_config_var("CC")
        ccompiler.compiler_cxx[0] = get_config_var("CXX")
        compiler = ccompiler.compiler
        compiler_cxx = ccompiler.compiler_cxx
    if compiler:
        os.environ.setdefault("CC", compiler[0])
    if compiler_cxx:
        os.environ.setdefault("CXX", compiler_cxx[0])


def _check_cpp_compiler_version(min_version: str):
    """Check if GCC compiler is >= min supported one, otherwise show warning"""
    try:
        cpp_compiler = os.environ.get("CXX", "")
        version = subprocess.run(
            [cpp_compiler, "--version"],
            stdout=subprocess.PIPE,
        ).stdout.decode("utf-8")
        if "gcc" in version.lower() or "gnu" in version.lower():
            version = subprocess.run(
                [cpp_compiler, "-dumpversion"],
                stdout=subprocess.PIPE,
            ).stdout.decode("utf-8")
            if Version(version) <= Version(min_version):
                warnings.warn(
                    f"Warning: GCC >= {min_version} is required with this version of NEURON"
                    f"but found version {version}",
                )
    except:
        pass


def _vendored_wheel_lib_dirs(site_packages):
    """delvewheel copies MSVCP140.dll into <package>.libs next to neuron/."""
    dirs = []
    site = Path(site_packages)
    for name in ("neuron_nightly.libs", "neuron.libs"):
        d = site / name
        if d.is_dir():
            dirs.append(str(d))
    return dirs


def _resolve_pylibs():
    """Fill NRN_PYLIB and NMODL_PYLIB without dropping an explicit NRN_PYLIB.

    install_instructions documents NRN_PYLIB as the override for which
    library nrniv loads. NMODL_PYLIB is kept when the caller set it.
    find_libpython() fills only the variables that are still empty.
    """
    nrn = os.environ.get("NRN_PYLIB") or None
    nmodl = os.environ.get("NMODL_PYLIB") or None
    discovered = None
    if not nrn or not nmodl:
        discovered = nmodl or nrn or find_libpython()
    if not nrn and not nmodl and not discovered:
        raise ValueError(
            "unable to locate the Python shared library; "
            "please make sure it is installed, "
            "or set the environmental variable `NRN_PYLIB` "
            "(or `NMODL_PYLIB`) manually to the path to the Python shared library"
        )
    if not nmodl:
        os.environ["NMODL_PYLIB"] = nrn or discovered
    if not nrn:
        os.environ["NRN_PYLIB"] = nmodl or discovered


def _config_exe(exe_name):
    """Sets the environment to run the real executable (returned)"""
    try:
        metadata("neuron-nightly")
        print("INFO : Using neuron-nightly Package (Developer Version)")
    except PackageNotFoundError:
        pass

    neuron_origin = Path(find_spec("neuron").origin)
    NRN_PREFIX = str(neuron_origin.parent / ".data")

    os.environ["NEURONHOME"] = os.path.join(NRN_PREFIX, "share/nrn")
    os.environ["NRNHOME"] = NRN_PREFIX
    os.environ["CORENRNHOME"] = NRN_PREFIX
    # nrniv skips bash nrnpyenv.sh only when all three NRN_PY* are set.
    os.environ["NRN_PYTHONEXE"] = sys.executable
    os.environ["CORENRN_PYTHONEXE"] = sys.executable
    os.environ["NRN_PYTHONVERSION"] = "{}.{}".format(*sys.version_info[:2])
    os.environ["NRNBIN"] = os.path.dirname(__file__)

    if "NMODLHOME" not in os.environ:
        os.environ["NMODLHOME"] = NRN_PREFIX
    _resolve_pylibs()

    # nmodl module is inside <prefix>/lib directory
    sys.path.insert(0, os.path.join(NRN_PREFIX, "lib"))
    os.environ["PYTHONPATH"] = os.pathsep.join(sys.path)

    bindir = os.path.join(NRN_PREFIX, "bin")
    path_dirs = [bindir]
    # Windows loads nrniv.exe's MSVCP140.dll from the exe directory, System32,
    # then PATH. AddDllDirectory in this process is not inherited. delvewheel
    # vendors that DLL in site-packages/*.libs (import neuron uses it).
    if os.name == "nt":
        path_dirs.extend(_vendored_wheel_lib_dirs(neuron_origin.parent.parent))
    os.environ["PATH"] = (
        os.pathsep.join(path_dirs) + os.pathsep + os.environ.get("PATH", "")
    )

    _set_default_compiler()
    exe = os.path.join(bindir, exe_name)
    if (
        os.name == "nt"
        and not exe.lower().endswith(".exe")
        and os.path.isfile(exe + ".exe")
    ):
        exe = exe + ".exe"
    return exe


def _wrap_executable(output_name):
    """Create a wrapper for an executable in same dir. Requires renaming the original file.
    Executables are typically found under arch_name
    """
    release_dir = os.path.join(os.environ["NEURONHOME"], "demo/release")
    arch_name = next(os.walk(release_dir))[1][0]  # first dir
    file_path = os.path.join(arch_name, output_name)
    shutil.move(file_path, file_path + ".nrn")
    shutil.copy(__file__, file_path)


def _wrapper_stem(argv0):
    """Command name without a Windows launcher suffix."""
    name = os.path.basename(argv0)
    if os.name == "nt":
        lower = name.lower()
        for suffix in (".exe", ".cmd", ".bat"):
            if lower.endswith(suffix):
                return name[: -len(suffix)]
    return name


def _nrnivmodl_help():
    print("Usage: nrnivmodl [options] [mod files or directories with mod files]")
    print("Options:")
    print('  -incflags "compile flags"       Extra flags for compiling MOD files.')
    print("                                  cl.exe takes /I and -I.")
    print('  -loadflags "link flags"         Extra flags for linking nrnmech.dll.')
    print(
        "                                  link.exe takes a .lib or /LIBPATH:, not gcc -L/-l."
    )
    print("  -h, --help                      Show this help message and exit.")
    print("  -coreneuron, -nmodl, and -nmodlflags are Unix nrnivmodl options.")
    print("  This build uses nocmodl and does not build CoreNEURON.")
    print(
        "If no MOD files or directories provided then MOD files from current directory are used."
    )


def _nrnivmodl_parse_args(args):
    """Options before the first MOD file, same as Unix nrnivmodl.

    ``-incflags`` and ``-loadflags`` take the next argument even when it
    starts with ``-`` or ``/``. The last copy of a repeated flag wins.
    """
    rest = list(args)
    incflags = ""
    loadflags = ""
    while rest and rest[0].startswith("-"):
        opt = rest.pop(0)
        if opt in ("-h", "--help"):
            return {
                "help": True,
                "incflags": incflags,
                "loadflags": loadflags,
                "rest": rest,
            }
        if opt == "-coreneuron":
            raise SystemExit(
                "nrnivmodl: -coreneuron is not enabled in this Windows wheel"
            )
        if opt in ("-nmodl", "-nmodlflags"):
            raise SystemExit(
                f"nrnivmodl: {opt} is not available in this Windows build "
                "(nocmodl, not the NMODL transpiler)"
            )
        if opt in ("-incflags", "-loadflags"):
            if not rest:
                raise SystemExit(f"nrnivmodl: {opt} needs a value")
            value = rest.pop(0)
            if opt == "-incflags":
                incflags = value
            else:
                loadflags = value
            continue
        raise SystemExit(f"{opt} unrecognized, check available CLI options with --help")
    return {"help": False, "incflags": incflags, "loadflags": loadflags, "rest": rest}


def _nrnivmodl_flag_defs(incflags, loadflags):
    """One CMake ``-D`` argument per string. Spaces and semicolons stay inside it."""
    defs = []
    if incflags:
        defs.append(f"-DNRNIVMODL_INCFLAGS={incflags}")
    if loadflags:
        defs.append(f"-DNRNIVMODL_LDFLAGS={loadflags}")
    return defs


def _collect_mod_files(args):
    """MOD files from each argument. A directory is expanded on its own.

    Unix nrnivmodl walks every argument independently: a directory
    contributes its *.mod files, a file is that file, and a prefix such
    as ``hh`` is accepted when ``hh.mod`` exists. ``foo.bar`` looks for
    ``foo.bar.mod`` (not ``foo.mod``). An existing file wins over the
    prefix. Requiring the directory to be the only argument rejected
    ``nrnivmodl channels synapses`` and ``nrnivmodl channels extra.mod``.
    """
    if not args:
        mods = sorted(Path(".").glob("*.mod"))
    else:
        mods = []
        for item in args:
            path = Path(item)
            if path.is_dir():
                mods.extend(sorted(path.glob("*.mod")))
            elif path.is_file():
                mods.append(path)
            else:
                prefixed = Path(str(path) + ".mod")
                mods.append(prefixed if prefixed.is_file() else path)
    resolved = []
    for mod in mods:
        if not mod.is_file():
            raise SystemExit(f"nrnivmodl: ERROR: Mod file {mod} does not exist!")
        resolved.append(mod.resolve())
    return resolved


def _nt_replace_file(path):
    """Remove a file Windows may still have mapped (WinError 5 on unlink)."""
    path = Path(path)
    try:
        os.chmod(path, stat.S_IWRITE)
    except OSError:
        pass
    try:
        path.unlink()
        return
    except OSError:
        pass
    bak = path.with_name(f"{path.name}.old.{os.getpid()}")
    try:
        path.rename(bak)
    except OSError as e:
        raise SystemExit(
            f"nrnivmodl: cannot replace {path}: {e}\n"
            "Close other NEURON windows and retry."
        ) from e
    try:
        bak.unlink()
    except OSError:
        pass


def _nt_replace_tree(path):
    """Move a previous VS -B tree aside. A mapped nrnmech.dll cannot be deleted
    (WinError 5) but the directory can be renamed."""
    path = Path(path)
    bak = path.with_name(f"{path.name}.old.{os.getpid()}")
    n = 0
    while bak.exists():
        n += 1
        bak = path.with_name(f"{path.name}.old.{os.getpid()}.{n}")
    try:
        path.rename(bak)
    except OSError as e:
        raise SystemExit(
            f"nrnivmodl: cannot replace {path}: {e}\n"
            "Close other NEURON windows and retry."
        ) from e
    try:
        shutil.rmtree(bak)
    except OSError:
        pass


def _nt_regular_file(path):
    path = Path(path)
    return path.is_file() and not path.is_symlink()


def _nt_cache_is_nrnivmodl(path):
    """True when CMakeCache.txt is from ``project(nrnivmodl)``."""
    if not _nt_regular_file(path):
        return False
    try:
        with path.open("r", encoding="utf-8", errors="replace") as handle:
            text = handle.read(262144)
    except OSError:
        return False
    for line in text.splitlines():
        line = line.strip()
        if not line or line.startswith("#") or line.startswith("//"):
            continue
        if line.startswith("NRNIVMODL_"):
            return True
        if line == "CMAKE_PROJECT_NAME:STATIC=nrnivmodl":
            return True
    return False


def _nt_neuron_build_tree(path):
    """True when path is a directory this nrnivmodl created.

    A link is not followed. The only ownership evidence is CMakeCache.txt:
    a non-comment ``NRNIVMODL_`` line, or
    ``CMAKE_PROJECT_NAME:STATIC=nrnivmodl``. A regular ``nrnmech.dll`` or
    ``nrnivmodl.sln`` does not count.
    """
    path = Path(path)
    if path.is_symlink() or not path.is_dir():
        return False
    return _nt_cache_is_nrnivmodl(path / "CMakeCache.txt")


def _nt_prepare_build_dir(path):
    """Clear a previous nrnivmodl build. Leave any other directory alone.

    The Windows wheel build directory is ``cwd / platform.machine()``
    (``AMD64``). Replacing that directory drops stale CMake state and a
    mapped ``nrnmech.dll``. The name is not reserved. A directory whose
    CMake cache is not this nrnivmodl project is refused, and nothing is
    removed.
    """
    path = Path(path)
    if not path.exists() and not path.is_symlink():
        return
    if _nt_neuron_build_tree(path):
        _nt_replace_tree(path)
        return
    raise SystemExit(
        f"nrnivmodl: {path} exists and is not a NEURON nrnivmodl build directory.\n"
        "nrnivmodl will not delete it. Move it aside, or run nrnivmodl "
        "from another directory."
    )


def _nrnivmodl_cmake(args):
    """Build nrnmech via the shipped neuron CMake package (Windows wheel path)."""
    parsed = _nrnivmodl_parse_args(args)
    if parsed["help"]:
        _nrnivmodl_help()
        return 0
    rest = parsed["rest"]

    print(os.getcwd())
    mods = _collect_mod_files(rest)
    if not mods:
        print("nrnivmodl: no MOD files to compile")
        return 0

    if os.name == "nt":
        from neuron._windows_cxx import (
            NRNIVMODL_WIN_TOOLS_MISSING,
            find_cmake,
            msvc_cl_available,
        )

        mingw = (
            Path(os.environ.get("NRNHOME", ""))
            / "mingw"
            / "mingw64"
            / "bin"
            / "x86_64-w64-mingw32-g++.exe"
        )
        cmake = find_cmake()
        if mingw.is_file():
            if not cmake:
                raise SystemExit(
                    "nrnivmodl: cmake not found; install CMake from https://cmake.org/download/"
                )
        elif not cmake or not msvc_cl_available():
            raise SystemExit(NRNIVMODL_WIN_TOOLS_MISSING.strip())
    else:
        cmake = shutil.which("cmake")
        if not cmake:
            raise SystemExit(
                "nrnivmodl: cmake not found on PATH; install CMake from https://cmake.org/download/"
            )

    prefix = Path(os.environ["NRNHOME"])
    srcdir = prefix / "lib" / "cmake" / "neuron" / "nrnivmodl"
    if not (srcdir / "CMakeLists.txt").is_file():
        raise SystemExit(f"nrnivmodl: missing {srcdir / 'CMakeLists.txt'}")

    units = prefix / "share" / "nrn" / "lib" / "nrnunits.lib"
    if units.is_file():
        os.environ.setdefault("MODLUNIT", str(units))

    # Match CMAKE_SYSTEM_PROCESSOR (AMD64 on win_amd64) and Unix uname -m layout.
    # Replace only a previous nrnivmodl tree. An unrelated AMD64 is left as it is.
    builddir = Path.cwd() / platform.machine()
    if os.name == "nt":
        _nt_prepare_build_dir(builddir)
    cmake_cfg = [
        cmake,
        "-S",
        str(srcdir),
        "-B",
        str(builddir),
        f"-DNRNIVMODL_MOD_FILES={';'.join(str(m) for m in mods)}",
        "-DNRNIVMODL_NEURON=ON",
        "-DNRNIVMODL_CORENEURON=OFF",
        "-DNRNIVMODL_SPECIAL=OFF",
        f"-DCMAKE_PREFIX_PATH={prefix}",
    ]
    cmake_cfg.extend(_nrnivmodl_flag_defs(parsed["incflags"], parsed["loadflags"]))
    gen = os.environ.get("CMAKE_GENERATOR", "")
    if os.name == "nt" and "Ninja" not in gen:
        cmake_cfg.extend(["-A", "x64"])

    subprocess.check_call(cmake_cfg)
    build_cmd = [cmake, "--build", str(builddir), "--parallel"]
    if os.name == "nt" and "Ninja" not in gen:
        # neuronTargets-release.cmake; VS defaults to Debug otherwise.
        build_cmd.extend(["--config", "Release"])
    subprocess.check_call(build_cmd)

    if os.name == "nt":
        dest = Path.cwd() / "nrnmech.dll"
        if dest.is_file():
            _nt_replace_file(dest)
        candidates = [
            builddir / "nrnmech.dll",
            builddir / "Release" / "nrnmech.dll",
            builddir / "RelWithDebInfo" / "nrnmech.dll",
            builddir / "Debug" / "nrnmech.dll",
        ]
        for src in candidates:
            if src.is_file():
                if src.resolve() != dest.resolve():
                    shutil.copy2(src, dest)
                print(f"nrnivmodl: {dest}")
                return 0
        raise SystemExit("nrnivmodl: nrnmech.dll was not produced")
    return 0


def _python_script(path):
    """True when the file's shebang names Python.

    Windows CreateProcess does not run a shebang. rdcellstate is Python.
    sortspike and mkthreadsafe are bash and are not wheel launchers.
    path is this launcher's own executable, not a request path.
    """
    try:
        with open(path, "rb") as handle:  # NOSONAR
            line = handle.readline(200)
    except OSError:
        return False
    if not line.startswith(b"#!"):
        return False
    return b"python" in line.lower()


def _windows_launch_argv(exe, args):
    """argv for CreateProcess. A Python script uses this interpreter."""
    if _python_script(exe):
        return [sys.executable, exe, *args]
    return [exe, *args]


def _posix_path(path):
    """Forward slashes: InterViews -dll style treats \\n in a Win32 path as newline."""
    return str(path).replace("\\", "/")


def _nrngui(args):
    """Port of bin/nrngui.in for Windows wheels (no bash).

    Unix: nrniv $NEURONHOME/lib/hoc/nrngui.hoc "$@" -
    .data/bin/nrngui is that bash script (Error 193, same as stock
    neurondemo). Hoc path uses forward slashes so InterViews style
    does not treat \\n in share\\nrn as newline.
    Trailing - reads stdin after nrngui.hoc (same as Unix). File argv
    ends like Unix; without -, the GUI would load and exit.
    """
    home = Path(os.environ["NEURONHOME"])
    hoc = home / "lib" / "hoc" / "nrngui.hoc"
    if not hoc.is_file():
        raise SystemExit(f"nrngui: missing {hoc}")
    nrniv = Path(os.environ["NRNHOME"]) / "bin" / "nrniv.exe"
    if not nrniv.is_file():
        raise SystemExit(f"nrngui: not a file: {nrniv}")
    cmd = [str(nrniv), _posix_path(hoc), *args, "-"]
    # Inherit stdin so a redirected file or a pipeline reaches the trailing '-'.
    # A CI job that leaves stdin open closes it in the test, not here.
    return subprocess.call(cmd)  # NOSONAR


def _neurondemo(args):
    """Port of bin/neurondemo.in for Windows wheels (no bash).

    The MSVC wheel ships share/nrn/demo/release/nrnmech.dll (built at
    wheel time). If that file is missing, compile with the same
    nrnivmodl CMake path as Test 4 (needs cl.exe). Then nrniv -dll
    that DLL demo.hoc. NRNDEMO is the HOC $(NRNDEMO) prefix (trailing
    slash). Unix appends '-' so stdin is read after demo.hoc; Windows
    does the same (file argv ends like Unix).
    """
    home = Path(os.environ["NEURONHOME"])
    demo = home / "demo"
    release = demo / "release"
    hoc = demo / "demo.hoc"
    if not hoc.is_file():
        raise SystemExit(f"neurondemo: missing {hoc}")
    if not release.is_dir():
        raise SystemExit(f"neurondemo: missing {release}")

    os.environ["NRNDEMO"] = _posix_path(demo) + "/"

    dll = release / "nrnmech.dll"
    if not dll.is_file():
        saved = Path.cwd()
        try:
            os.chdir(release)
            rc = _nrnivmodl_cmake([])
        finally:
            os.chdir(saved)
        if rc:
            return rc
        if not dll.is_file():
            raise SystemExit(f"neurondemo: nrnivmodl did not produce {dll}")

    nrniv = Path(os.environ["NRNHOME"]) / "bin" / "nrniv.exe"
    if not nrniv.is_file():
        raise SystemExit(f"neurondemo: not a file: {nrniv}")
    cmd = [str(nrniv), "-dll", _posix_path(dll), _posix_path(hoc), *args, "-"]
    # Inherit stdin so a redirected file or a pipeline reaches the trailing '-'.
    # A CI job that leaves stdin open closes it in the test, not here.
    return subprocess.call(cmd)  # NOSONAR


if __name__ == "__main__":
    wrapper_name = _wrapper_stem(sys.argv[0])
    exe = _config_exe(wrapper_name)

    if wrapper_name == "nrngui" and os.name == "nt":
        sys.exit(_nrngui(sys.argv[1:]))

    if wrapper_name == "neurondemo" and os.name == "nt":
        sys.exit(_neurondemo(sys.argv[1:]))

    if wrapper_name.startswith("nrnivmodl"):
        if os.name == "nt":
            if wrapper_name in ("nrnivmodl-core", "nrnivmodl-all-cmake"):
                raise SystemExit("nrnivmodl-core is not enabled in this Windows wheel")
            sys.exit(_nrnivmodl_cmake(sys.argv[1:]))
        # To create a wrapper for special (so it also gets ENV vars) we intercept nrnivmodl
        _check_cpp_compiler_version("10.0")
        subprocess.check_call([exe, *sys.argv[1:]])
        _wrap_executable("special")
        sys.exit(0)

    if exe.endswith("special"):
        exe = os.path.join(
            sys.argv[0] + ".nrn"
        )  # original special is renamed special.nrn

    if os.name == "nt":
        # os.execv is not exec on Windows: it rebuilds a command line with
        # MSVCRT quoting, which splits -c statements that contain spaces
        # (print "hello"). subprocess.call with a list is argv, not a shell
        # (list2cmdline, same as nrnivmodl). CreateProcess does not read a
        # shebang, so a Python script is started with this interpreter.
        if not os.path.isfile(exe):
            raise SystemExit(f"neuron wrapper: not a file: {exe}")
        argv = _windows_launch_argv(exe, sys.argv[1:])
        raise SystemExit(subprocess.call(argv))  # NOSONAR
    os.execv(exe, sys.argv)
