# Copyright (c) ONNX Project Contributors
#
# SPDX-License-Identifier: Apache-2.0
import glob
import multiprocessing
import os
import platform
import re
import shlex
import shutil
import subprocess
import sys
from contextlib import contextmanager
from distutils import log, sysconfig
from textwrap import dedent
from typing import ClassVar, NamedTuple

import setuptools
import setuptools.command.build_ext
import setuptools.command.build_py
import setuptools.command.develop

TOP_DIR = os.path.realpath(os.path.dirname(__file__))
SRC_DIR = os.path.join(TOP_DIR, "onnxoptimizer")
CMAKE_BUILD_DIR = os.path.join(
    TOP_DIR, ".setuptools-cmake-build{}.{}".format(*sys.version_info[:2])
)

WINDOWS = os.name == "nt"
MACOS = sys.platform.startswith("darwin")

CMAKE = shutil.which("cmake")

################################################################################
# Global variables for controlling the build variant
################################################################################

USE_MSVC_STATIC_RUNTIME = bool(os.getenv("USE_MSVC_STATIC_RUNTIME", "0") == "1")
ONNX_ML = not bool(os.getenv("ONNX_ML") == "0")
ONNX_VERIFY_PROTO3 = bool(os.getenv("ONNX_VERIFY_PROTO3") == "1")
ONNX_NAMESPACE = os.getenv("ONNX_NAMESPACE", "onnx")
ONNX_BUILD_TESTS = bool(os.getenv("ONNX_BUILD_TESTS") == "1")
ONNX_OPT_USE_SYSTEM_PROTOBUF = bool(os.getenv("ONNX_OPT_USE_SYSTEM_PROTOBUF", "0") == "1")
ONNX_USE_LITE_PROTO = bool(os.getenv("ONNX_USE_LITE_PROTO", "1") == "1")

DEBUG = bool(os.getenv("DEBUG"))
COVERAGE = bool(os.getenv("COVERAGE"))

################################################################################
# Version
################################################################################

try:
    git_version = (
        subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=TOP_DIR)
        .decode("ascii")
        .strip()
    )
except (OSError, subprocess.CalledProcessError):
    git_version = None


class VersionInfo(NamedTuple):
    version: str
    git_version: str | None


with open(os.path.join(TOP_DIR, "VERSION_NUMBER")) as version_file:
    version_info = VersionInfo(version=version_file.read().strip(), git_version=git_version)

################################################################################
# Pre Check
################################################################################

assert CMAKE, 'Could not find "cmake" executable!'

################################################################################
# Utilities
################################################################################


@contextmanager
def cd(path):
    if not os.path.isabs(path):
        raise RuntimeError(f"Can only cd to absolute path, got: {path}")
    orig_path = os.getcwd()
    os.chdir(path)
    try:
        yield
    finally:
        os.chdir(orig_path)


################################################################################
# Customized commands
################################################################################


class ONNXCommand(setuptools.Command):
    user_options: ClassVar[list] = []

    def initialize_options(self):
        pass

    def finalize_options(self):
        pass


class create_version(ONNXCommand):
    def run(self):
        with open(os.path.join(SRC_DIR, "version.py"), "w") as f:
            f.write(
                dedent(
                    """\
            # This file is generated by setup.py. DO NOT EDIT!

            version = '{version}'
            git_version = '{git_version}'
            """.format(**dict(version_info._asdict()))
                )
            )


class cmake_build(setuptools.Command):
    """
    Compiles everything when `python setupmnm.py build` is run using cmake.

    Custom args can be passed to cmake by specifying the `CMAKE_ARGS`
    environment variable.

    The number of CPUs used by `make` can be specified by passing `-j<ncpus>`
    to `setup.py build`.  By default all CPUs are used.
    """

    user_options: ClassVar[list] = [
        ("jobs=", "j", "Specifies the number of jobs to use with make")
    ]

    built = False

    def initialize_options(self):
        self.jobs = None

    def finalize_options(self):
        self.set_undefined_options("build", ("parallel", "jobs"))
        if self.jobs is None and os.getenv("MAX_JOBS") is not None:
            self.jobs = os.getenv("MAX_JOBS")
        self.jobs = multiprocessing.cpu_count() if self.jobs is None else int(self.jobs)

    def run(self):
        if cmake_build.built:
            return
        cmake_build.built = True
        if not os.path.exists(CMAKE_BUILD_DIR):
            os.makedirs(CMAKE_BUILD_DIR)

        with cd(CMAKE_BUILD_DIR):
            build_type = "Release"
            # configure
            cmake_args = [
                CMAKE,
                f"-DPython_INCLUDE_DIR={sysconfig.get_python_inc()}",
                f"-DPython_EXECUTABLE={sys.executable}",
                "-DONNX_BUILD_PYTHON=ON",
                "-DCMAKE_EXPORT_COMPILE_COMMANDS=ON",
                f"-DONNX_NAMESPACE={ONNX_NAMESPACE}",
                "-DONNX_OPT_USE_SYSTEM_PROTOBUF={}".format(
                    "ON" if ONNX_OPT_USE_SYSTEM_PROTOBUF else "OFF"
                ),
            ]
            if COVERAGE:
                cmake_args.append("-DONNX_COVERAGE=ON")
            if COVERAGE or DEBUG:
                # in order to get accurate coverage information, the
                # build needs to turn off optimizations
                build_type = "Debug"
            cmake_args.append(f"-DCMAKE_BUILD_TYPE={build_type}")
            if WINDOWS:
                cmake_args.extend(
                    [
                        # we need to link with libpython on windows, so
                        # passing python version to window in order to
                        # find python in cmake
                        "-DPY_VERSION={}".format("{}.{}".format(*sys.version_info[:2])),
                    ]
                )
                if USE_MSVC_STATIC_RUNTIME:
                    cmake_args.append("-DONNX_USE_MSVC_STATIC_RUNTIME=ON")
                if platform.architecture()[0] == "64bit":
                    cmake_args.extend(["-A", "x64", "-T", "host=x64"])
                else:
                    cmake_args.extend(["-A", "Win32", "-T", "host=x86"])
            if MACOS:
                # Cross-compile support for macOS - respect ARCHFLAGS if set
                archs = re.findall(r"-arch (\S+)", os.environ.get("ARCHFLAGS", ""))
                if archs:
                    cmake_args += ["-DCMAKE_OSX_ARCHITECTURES={}".format(";".join(archs))]
            if ONNX_ML:
                cmake_args.append("-DONNX_ML=1")
            if ONNX_VERIFY_PROTO3:
                cmake_args.append("-DONNX_VERIFY_PROTO3=1")
            if ONNX_BUILD_TESTS:
                cmake_args.append("-DONNX_BUILD_TESTS=ON")
            if "CMAKE_ARGS" in os.environ:
                extra_cmake_args = shlex.split(os.environ["CMAKE_ARGS"])
                # prevent crossfire with downstream scripts
                del os.environ["CMAKE_ARGS"]
                log.info(f"Extra cmake args: {extra_cmake_args}")
                cmake_args.extend(extra_cmake_args)
            cmake_args.append(TOP_DIR)
            subprocess.check_call(cmake_args)

            build_args = [CMAKE, "--build", os.curdir]
            if WINDOWS:
                build_args.extend(["--config", build_type])
                build_args.extend(["--", f"/maxcpucount:{self.jobs}"])
            else:
                build_args.extend(["--", "-j", str(self.jobs)])
            subprocess.check_call(build_args)


class build_py(setuptools.command.build_py.build_py):
    def run(self):
        self.run_command("create_version")
        self.run_command("cmake_build")

        generated_python_files = glob.glob(
            os.path.join(CMAKE_BUILD_DIR, "onnxoptimizer", "*.py")
        ) + glob.glob(os.path.join(CMAKE_BUILD_DIR, "onnxoptimizer", "*.pyi"))

        for src in generated_python_files:
            dst = os.path.join(TOP_DIR, os.path.relpath(src, CMAKE_BUILD_DIR))
            self.copy_file(src, dst)

        return setuptools.command.build_py.build_py.run(self)


class develop(setuptools.command.develop.develop):
    def run(self):
        self.run_command("build_py")
        setuptools.command.develop.develop.run(self)


class build_ext(setuptools.command.build_ext.build_ext):
    def run(self):
        self.run_command("cmake_build")
        setuptools.command.build_ext.build_ext.run(self)

    def build_extensions(self):
        for ext in self.extensions:
            fullname = self.get_ext_fullname(ext.name)
            filename = os.path.basename(self.get_ext_filename(fullname))

            lib_path = CMAKE_BUILD_DIR
            if os.name == "nt":
                debug_lib_dir = os.path.join(lib_path, "Debug")
                release_lib_dir = os.path.join(lib_path, "Release")
                if os.path.exists(debug_lib_dir):
                    lib_path = debug_lib_dir
                elif os.path.exists(release_lib_dir):
                    lib_path = release_lib_dir
            src = os.path.join(lib_path, filename)
            lib_dir = os.path.join(os.path.realpath(self.build_lib), "onnxoptimizer")
            dst = os.path.realpath(os.path.join(lib_dir, filename))
            os.makedirs(lib_dir, exist_ok=True)
            self.copy_file(src, dst)


class mypy_type_check(ONNXCommand):
    description = "Run MyPy type checker"

    def run(self):
        """Run command."""
        onnx_script = os.path.realpath(
            os.path.join(os.path.dirname(os.path.abspath(__file__)), "tools/mypy-onnx.py")
        )
        returncode = subprocess.call([sys.executable, onnx_script])
        sys.exit(returncode)


cmdclass = {
    "create_version": create_version,
    "cmake_build": cmake_build,
    "build_py": build_py,
    "develop": develop,
    "build_ext": build_ext,
    "typecheck": mypy_type_check,
}

################################################################################
# Extensions
################################################################################

################################################################################
# Extensions
################################################################################

# Enable limited ABI build
# nanobind supports limited ABI for Python 3.12 and later.
# https://blog.trailofbits.com/2022/11/15/python-wheels-abi-abi3audit/
# 1. The Py_LIMITED_API macro is defined in the extension
# 2. py_limited_api in Extension tags the extension as abi3
# 3. bdist_wheel options tag the wheel as abi3
NO_GIL = hasattr(sys, "_is_gil_enabled") and not sys._is_gil_enabled()
PY_312_OR_NEWER = sys.version_info >= (3, 12)
USE_LIMITED_API = not NO_GIL and PY_312_OR_NEWER and platform.system() != "FreeBSD"

macros = []
if USE_LIMITED_API:
    macros.append(("Py_LIMITED_API", "0x030C0000"))

ext_modules = [
    setuptools.Extension(
        name="onnxoptimizer.onnx_opt_cpp2py_export",
        sources=[],
        py_limited_api=USE_LIMITED_API,
        define_macros=macros,
    )
]

################################################################################
# Packages
################################################################################

# no need to do fancy stuff so far
packages = setuptools.find_packages()

################################################################################
# Test
################################################################################

bdist_wheel_options = {}
if USE_LIMITED_API:
    bdist_wheel_options["py_limited_api"] = "cp312"

setup_opts = {}
if bdist_wheel_options:
    setup_opts["bdist_wheel"] = bdist_wheel_options

setuptools.setup(
    version=version_info.version,
    ext_modules=ext_modules,
    cmdclass=cmdclass,
    packages=packages,
    include_package_data=True,
    options=setup_opts,
)
