#!/usr/bin/env python3

import argparse
import os
import subprocess
import sys
from pathlib import Path


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--bytecode-roundtrip', action='store_true',
                        help='Write and reload programs before creating test engines')
    parser.add_argument('--python', help='Python executable name or path')
    parser.add_argument('--timings', action='store_true',
                        help='List test durations, slowest first, at the end')
    parser.add_argument('--keep-going', action='store_true',
                        help='Run the remaining tests after a failure and list the failed tests at the end')
    parser.add_argument('--processes', type=int, default=1, metavar='N',
                        help='Run tests in N worker processes (default: 1, serial)')
    parser.add_argument('--threads', type=int, default=1, metavar='N',
                        help='Run up to N tests concurrently in each worker process (default: 1)')
    parser.add_argument('names', nargs='*', metavar='TEST',
                        help='Extensionless test names or directories (default: all tests)')
    args = parser.parse_intermixed_args()
    python = args.python
    if python and (os.sep in python or (os.altsep and os.altsep in python)):
        python = str(Path(python).absolute())
    repository_root = Path(__file__).resolve().parent.parent
    venv_python = repository_root / 'venv' / 'bin' / 'python'
    if python is None:
        if venv_python.is_file():
            python = str(venv_python)
        else:
            print('Warning: venv not found; run tools/setup-venv to install dependencies.',
                  file=sys.stderr)
            python = sys.executable

    os.chdir(repository_root)
    runner_args = (['--timings'] if args.timings else []) + (['--keep-going'] if args.keep_going else [])
    runner_args += ['--processes', str(args.processes), '--threads', str(args.threads)]
    if args.bytecode_roundtrip:
        runner_args.append('--bytecode-roundtrip')
    return subprocess.run(
        [python, '-m', 'tests.infra.runner', *runner_args, *args.names],
    ).returncode


if __name__ == '__main__':
    sys.exit(main())
