#!/usr/bin/env python3 -B
"""
Run basic tests on the wheels archives.

Run this after running "collect-dist-archives"
"""
import os
import subprocess
import sys

from _common_definitions import (
    DIST_DIR,
    PY_VERSIONS,
    setup_variant,
    variants,
    virtualenv,
)


def pyobjc_ver():
    for nm in os.listdir(DIST_DIR):
        if nm.startswith("pyobjc-core"):
            ver = nm.split("-")[-1].replace(".tar.gz", "")
            return ver

    raise RuntimeError("Cannot determine version of PyObjC")


def main():
    for ver in PY_VERSIONS:
        for variant in variants(ver):
            setup_variant(ver, variant)

            with virtualenv(f"python{ver}") as interpreter:
                log = subprocess.check_output(
                    [
                        interpreter,
                        "-mpip",
                        "install",
                        "-f",
                        DIST_DIR,
                        "--no-index",
                        "--no-cache-dir",
                        f"pyobjc=={pyobjc_ver()}",
                    ]
                ).decode("utf-8")

                sys.stdout.write(log)
                if "Building wheels for collected packages" in log:
                    print(f"WARNING: non-wheel install: {ver}")
                    sys.exit(1)
                for ln in log.splitlines():
                    if (
                        "Running setup.py install" in ln
                        and "Running setup.py install for pyobjc:" not in ln
                    ):
                        print(f"WARNING: non-wheel install: {ver}")
                        sys.exit(1)

                subprocess.check_call(
                    [
                        interpreter,
                        os.path.join(os.path.dirname(__file__), "wheel-smoke-test.py"),
                    ]
                )


if __name__ == "__main__":
    main()
