"""
Determine the wheel name via setuptools

Usage:
$ python3 wheelname.py <package-name> <version-string>
"""

from setuptools import Extension, Distribution
import platform

HEADER = "wheelname.py"

def wheel_tags(**kwargs):
    """ set up a dummy distribution from arguments
    and return a resulting wheel name
    """

    dst = Distribution(attrs=kwargs)
    # finalize bdist_wheel command
    bdist_wheel_cmd = dst.get_command_obj('bdist_wheel')
    bdist_wheel_cmd.ensure_finalized()

    distname = bdist_wheel_cmd.wheel_dist_name  # eg. 'testdist-1.2.3'
    tags = bdist_wheel_cmd.get_tag() # eg. (cp311, cp311, linux_x86_64)

    return (distname, *tags)


def wheel_tag_mac_x64(distname, py_tag, abi_tag, platform_tag):
    """ Ad-hoc fix for the platform tag for conda under MacOS-x64.

    Python binaries under conda platform are compiled with an old MacOS (10.9)
    in order to be compatible with later MacOS versions.
    Therefore, under MacOS, conda's `pip` considers binaries compiled and linked
    with higher MacOS versions as _invalid_.
    A quick and dirty fix is changing the platform tag to 'macosx_10_9_x86_64'.

    NOTE: Use `python3 -m pip debug -vvv` to obtain valid wheel names
      under a Python platform.
    """

    if platform.system().lower() == 'darwin' and platform.machine() == 'x86_64':
        # platform tag compatible with MacOS-x64 conda Python platform
        platform_tag = "macosx_10_9_x86_64"

    return (distname, py_tag, abi_tag, platform_tag)


def wheel_name(*tags):
    # eg. 'testdist-1.2.3-cp311-cp311-linux_x86_64'
    return '-'.join(*tags)


def get_wheel_names(pkg_name:str, version_str:str):
    # get the name of the pure-Python wheel
    pure_tags = wheel_tags(name=pkg_name, version=version_str)
    pure_whl = wheel_name(pure_tags)

    # get tags for the platform-dependent wheel
    plt_tags = wheel_tags(name=pkg_name, version=version_str,
                          ext_modules=[Extension("dummylib", ["dummy.c"])])
    # fix platform tag to be compatible with conda under MacOS-x64
    platform_tags = wheel_tag_mac_x64(*plt_tags)
    platform_whl = wheel_name(platform_tags)

    # NOTE: CMake list separator is semicolon
    return ';'.join((pure_whl, platform_whl))

#----------------------------------------

if __name__ == "__main__":
    import sys

    args = sys.argv
    if len(args) <= 2:
        print("Usage: python3 wheelname.py <package-name> <version-string>")
        raise ValueError(HEADER + ": package name and version string must be non-empty.")

    pkg_name = args[1].strip()
    version_str = args[2].strip()
    print(get_wheel_names(pkg_name, version_str))
