#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Extra custom params:

--only-pure            Build a pure-Python Wheel
--windows-cross-pack   Pack with a pre-built Windows "_speedups.pyd".
                       Most likely "-p win_amd64" is needed also.

"""

from __future__ import print_function, absolute_import

import re
import os
import platform
import shutil
import sys
try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup


PROJECT_NAME = "ConfigMix"


if (sys.version_info[0] < 2) or \
        ((sys.version_info[0] == 2) and (sys.version_info[1] < 6)):
    raise ValueError("Need at least Python 2.6")

pkg_root = os.path.dirname(__file__)

_version_re = re.compile(br"^\s*__version__\s*=\s*(\"|')(.*)\1\s*(#.*)?$",
                         re.MULTILINE)

with open(os.path.join(pkg_root, "configmix", "__init__.py"), "rb") as vf:
    version = _version_re.search(vf.read()).group(2).decode("utf-8")

with open(os.path.join(pkg_root, "README.txt"), "rt") as rf:
    long_description = rf.read()

aws_requirements = [
    "requests",
]

yaml_requirements = [
    "PyYAML>=3.0,<7",
]

toml_requirements = [
    "toml>=0.10",
]

sasl_requirements = [
    "passlib>=1.6",
]

all_requirements = []
all_requirements.extend(aws_requirements)
all_requirements.extend(yaml_requirements)
all_requirements.extend(toml_requirements)
all_requirements.extend(sasl_requirements)


cmdclass = {}
ext_modules = None
setup_extra_kwds = {}

windows_cross_pack = False

try:
    wcp_idx = sys.argv.index("--windows-cross-pack")
except ValueError:
    wcp_idx = None
else:
    del sys.argv[wcp_idx]
try:
    pure_only_idx = sys.argv.index("--pure-only")
except ValueError:
    pure_only_idx = None
else:
    del sys.argv[pure_only_idx]


#
# Otherwise some cached package_data would be used.
# But our package data differs between "standard" builds and
# builds with "--windows-cross-pack".
#
if os.path.isdir(PROJECT_NAME + ".egg-info"):
    print("removing `%s.egg-info'" % (PROJECT_NAME,))
    shutil.rmtree(PROJECT_NAME + ".egg-info")

if pure_only_idx is None:
    if wcp_idx is None:
        #
        # The C-extension uses multi-phase module initialization
        # (PEP 489) which is PY 3.5+.
        #
        if (platform.python_implementation() == "CPython"
            and (sys.version_info[0] > 3
                 or (sys.version_info[0] == 3 and sys.version_info[1] >= 5))):

            # The stable API for Python 3.7+ is used
            if sys.version_info[0] == 3 and sys.version_info[1] < 7:
                py_limited_api = False
            else:
                py_limited_api = True

            if py_limited_api:
                define_macros = [("Py_LIMITED_API", "0x03070000")]
            else:
                define_macros = []

            try:
                from setuptools import Extension
            except ImportError:
                from distutils.core import Extension

            ext_modules = [
                Extension(
                    name="configmix._speedups",
                    sources=["configmix/_speedups.c"],
                    define_macros=define_macros,
                    py_limited_api=py_limited_api,
                    optional=True
                ),
            ]

            if py_limited_api:
                #
                # Build a wheel that is properly named using the stable API
                #
                try:
                    import wheel.bdist_wheel
                except ImportError:
                    pass
                else:
                    class BDistWheel(wheel.bdist_wheel.bdist_wheel):
                        def finalize_options(self):
                            # Synchronize this with Py_LIMITED_API
                            self.py_limited_api = 'cp37'
                            super().finalize_options()

                    cmdclass["bdist_wheel"] = BDistWheel
    else:

        if not os.path.isfile("configmix/_speedups.pyd"):
            raise RuntimeError("no _speedups.pyd found")

        setup_extra_kwds["package_data"] = {
            "configmix": ["*.pyd"]
        }

        ext_modules = []

        py_limited_api = True

        if py_limited_api:
            #
            # Build a wheel that is properly named using the stable API
            #
            try:
                import wheel.bdist_wheel
            except ImportError:
                pass
            else:
                class BDistWheel(wheel.bdist_wheel.bdist_wheel):
                    def finalize_options(self):
                        #
                        # Synchronize this with Py_LIMITED_API and with the
                        # external build of _speedups.pyd.
                        # Also use the --plat-name (-p) for tagging the Wheel
                        # properly (e.g. -p win_amd64).
                        #
                        self.py_limited_api = 'cp37'
                        super().finalize_options()

                cmdclass["bdist_wheel"] = BDistWheel


            #
            # Force installation into `platlib` instead of `purelib`.
            #
            # See also: https://peps.python.org/pep-0491/
            # See also: https://github.com/google/or-tools/issues/616
            #
            from setuptools.command.install import install

            class InstallPlatlib(install):
                def finalize_options(self):
                    super().finalize_options()
                    if self.distribution.has_ext_modules():
                        self.install_lib = self.install_platlib

            cmdclass["install"] = InstallPlatlib

        from setuptools.dist import Distribution

        #
        # Force a binary package. An empty ext_modules does not do this always.
        # Tested with wheel v0.29.0
        #
        class BinaryDistribution(Distribution):
            """Distribution which always forces a binary package with

            platform name

            """
            def has_ext_modules(foo):
                return True

        setup_extra_kwds["distclass"] = BinaryDistribution
else:
    #
    # pure
    #
    pass


if ext_modules is not None:
    setup_extra_kwds["ext_modules"] = ext_modules
    setup_extra_kwds["zip_safe"] = False
else:
    setup_extra_kwds["zip_safe"] = True
if cmdclass:
    setup_extra_kwds["cmdclass"] = cmdclass

setup(
    name=PROJECT_NAME,
    version=version,
    author="Franz Glasner",
    license='BSD 3-Clause "New" or "Revised" License',
    url="https://pypi.dom66.de/simple/configmix/",
    description="Library for extended configuration files",
    long_description=long_description,
    long_description_content_type="text/x-rst",
    packages=["configmix",
              "configmix.extras"],
    #
    # Use non-automatic explicit package_data instead
    # (or MANIFEST.in for sdist)
    #
    include_package_data=False,
    platforms="any",
    classifiers=[
        "Development Status :: 5 - Production/Stable",
        "Environment :: Console",
        "Intended Audience :: Developers",
        "License :: OSI Approved :: BSD License",
        "Operating System :: OS Independent",
        "Programming Language :: Python",
        "Programming Language :: Python :: 2.6",
        "Programming Language :: Python :: 2.7",
        "Programming Language :: Python :: 3",
        "Topic :: Software Development :: Libraries :: Python Modules"
    ],
    python_requires=">=2.6",
    extras_require={
        "aws":  aws_requirements,    # noqa: E241
        "toml": toml_requirements,
        "yaml": yaml_requirements,
        "sasl": sasl_requirements,
        "all":  all_requirements,    # noqa: E241
    },
    tests_require=all_requirements,
    **setup_extra_kwds
)
