#!/usr/bin/python3
# SPDX-FileCopyrightText: Peter Pentchev <roam@ringlet.net>
# SPDX-License-Identifier: BSD-2-Clause
"""Run the feature-check test suite with several Python interpreters."""

from __future__ import annotations

import os
import pathlib
import re
import shlex
import subprocess  # noqa: S404
import sys
import typing


if typing.TYPE_CHECKING:
    from typing import Final


PY_BASE_PATH: Final = pathlib.Path("/usr/bin")
"""The path where the Python interpreters live."""


def find_interpreters() -> list[pathlib.Path]:
    """Determine the list of supported Python interpreters."""
    paths: Final = [
        PY_BASE_PATH / line
        for line in re.split(
            r"[ \t\r\n]",
            subprocess.check_output(  # noqa: S603
                ["py3versions", "-s"],  # noqa: S607
                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'{shlex.quote(str(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)  # noqa: S603,S607

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


if __name__ == "__main__":
    main()
