from __future__ import annotations

import importlib
import sys

from setuptools import setup

try:
    _wheel_module = importlib.import_module("setuptools.command.bdist_wheel")
    _bdist_wheel = getattr(_wheel_module, "bdist_wheel")
except Exception:
    try:
        _wheel_module = importlib.import_module("wheel.bdist_wheel")
        _bdist_wheel = getattr(_wheel_module, "bdist_wheel")
    except Exception:
        _bdist_wheel = None


def _platform_package_data() -> dict[str, list[str]]:
    if sys.platform.startswith("win"):
        return {"pyinstaller_plus": ["bin/distromate.exe", "bin/resource/**"]}
    return {"pyinstaller_plus": ["bin/distromate"]}


def _normalize_linux_platform_tag(tag: str) -> str:
    if not tag.startswith("linux_"):
        return tag

    arch = tag.split("_", 1)[1]
    mapping = {
        "x86_64": "manylinux_2_17_x86_64.manylinux2014_x86_64",
        "i686": "manylinux_2_17_i686.manylinux2014_i686",
        "aarch64": "manylinux_2_17_aarch64.manylinux2014_aarch64",
        "ppc64le": "manylinux_2_17_ppc64le.manylinux2014_ppc64le",
        "s390x": "manylinux_2_17_s390x.manylinux2014_s390x",
    }
    return mapping.get(arch, tag)


cmdclass: dict[str, type] = {}
if _bdist_wheel is not None:

    class _PlatformWheel(_bdist_wheel):
        def finalize_options(self) -> None:
            super().finalize_options()
            self.root_is_pure = False

        def get_tag(self) -> tuple[str, str, str]:
            _, _, plat = super().get_tag()
            if sys.platform.startswith("linux"):
                plat = _normalize_linux_platform_tag(plat)
            return "py3", "none", plat

    cmdclass["bdist_wheel"] = _PlatformWheel


setup(
    packages=["pyinstaller_plus"],
    include_package_data=False,
    package_data=_platform_package_data(),
    cmdclass=cmdclass,
)
