#!/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,
    setup_variant,
    variants,
    virtualenv,
    detect_pyversions,
    BOLD,
    RESET,
)


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

    raise RuntimeError("Cannot determine version of PyObjC")


def main():
    install_version = pyobjc_ver()

    for ver in detect_pyversions():
        for variant in variants(ver):
            print(f"{BOLD}Testing PyObjC {install_version} for Python {variant}{RESET}")
            setup_variant(ver, variant)

            print("  create virtual env")
            with virtualenv(f"python{ver}") as interpreter:
                print("  installing")
                log = subprocess.check_output(
                    [
                        interpreter,
                        "-mpip",
                        "install",
                        "-f",
                        DIST_DIR,
                        "--no-index",
                        "--no-cache-dir",
                        "--only-binary",
                        ":all:",
                        f"pyobjc=={install_version}",
                    ]
                ).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)

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


if __name__ == "__main__":
    main()
