#!/usr/bin/python3
"""Run the feature-check test suite with several Python interpreters."""

from __future__ import annotations

import os
import pathlib
import re
import subprocess
import sys
import typing


if typing.TYPE_CHECKING:
    from typing import Final


def find_interpreters() -> list[pathlib.Path]:
    """Determine the list of supported Python interpreters."""
    paths: Final = [
        pathlib.Path("/usr/bin/" + line)
        for line in re.split(
            r"[ \t\r\n]",
            subprocess.check_output(["py3versions", "-s"], shell=False, encoding="UTF-8"),
        )
        if line
    ]
    missing: Final = [path for path in paths if not path.is_file()]
    if missing:
        sys.exit(
            "Missing/invalid Python interpreters: {missing}".format(
                missing=" ".join(map(str, missing))
            )
        )

    return paths


def main() -> None:
    """Fetch the list of interpreters, run things."""
    if hasattr(sys.stdout, "reconfigure"):
        sys.stdout.reconfigure(line_buffering=True)

    interpreters: Final = find_interpreters()

    test_script: Final = pathlib.Path("test-python/python/python-fcheck.sh")
    test_script.parent.mkdir(mode=0o755, parents=True, exist_ok=True)

    test_env: Final = dict(os.environ)
    test_env["TEST_PROG"] = str(test_script)

    for interp in interpreters:
        print(f"\n\n============ Testing {interp}\n")
        test_script.write_text(
            f"'{interp}' -m feature_check \"$@\"",
            encoding="UTF-8",
        )
        print(test_script.read_text(encoding="UTF-8"))
        test_script.chmod(0o755)

        subprocess.check_call(["prove", "t"], shell=False, env=test_env)

    print("\n\n============ The TAP tests passed for all Python versions\n")


if __name__ == "__main__":
    main()
