#!/usr/bin/env python3

import argparse
import os
from pathlib import Path

import launch


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('--show-logs', action='store_true',
                        help='Print the log messages of all tests, not only of failed ones')
    parser.add_argument('--no-capture', action='store_true',
                        help='Let tests write to the terminal directly, for example for breakpoint(), '
                             'and print a line for each test; requires a serial run')
    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())
    os.chdir(launch.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')
    if args.show_logs:
        runner_args.append('--show-logs')
    if args.no_capture:
        runner_args.append('--no-capture')
    launch.exec_module('tests.infra.runner', [*runner_args, *args.names], python=python)


if __name__ == '__main__':
    main()
