#!/usr/bin/env python3
"""ci/suite [-j N] [CLASS...]: the test suite, each test class in a process of its own, N classes at a time.

The classes are the ones `python3 -m unittest discover -s tests` finds, and each runs as it runs there: its
setUpClass and its tests in one process, in the order unittest gives them. A test holds a tree, a HOME and
PP_* directories of its own (tests/sandbox.py), and a journey a home of its own (tests/journey.py), so two
classes at once share nothing a test reads. The classes with the most tests start first, so the long ones
do not start last. N is twice the CPUs this process may run on (taskset), since a test spends most of its
time waiting on the processes it starts, and at most 16, past which the longest class is the run's floor.

The output is unittest's own: what a failing class printed, then the count and the outcome."""
from __future__ import annotations

import argparse
import os
import re
import subprocess
import sys
import time
import unittest
from concurrent.futures import ThreadPoolExecutor, as_completed

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TESTS = os.path.join(ROOT, "tests")
# one class, run as `python3 -m unittest -s tests` would run it: the tests directory first on the path
RUN = "import sys, unittest; sys.path.insert(0, sys.argv[1]); unittest.main(module=None, argv=['ci/suite', '-q', *sys.argv[2:]])"


def classes() -> dict[str, int]:
    """Every test class discovery finds, with its number of tests. A module that does not import is a unit of
    its own, so its error is reported as unittest reports it."""
    sys.path.insert(0, TESTS)
    found: dict[str, int] = {}

    def walk(suite):
        for t in suite:
            if isinstance(t, unittest.TestSuite):
                walk(t)
            elif type(t).__name__ == "_FailedTest":
                found[t.id().rsplit(".", 1)[1]] = 1
            else:
                name = f"{type(t).__module__}.{type(t).__name__}"
                found[name] = found.get(name, 0) + 1
    walk(unittest.TestLoader().discover(TESTS, top_level_dir=TESTS))
    return found


def run(unit: str) -> tuple[str, int, str, str, float]:
    """-> the class, how many tests ran, unittest's outcome line, all it printed, and how long it took."""
    t = time.monotonic()
    r = subprocess.run([sys.executable, "-c", RUN, TESTS, unit], cwd=ROOT, stdin=subprocess.DEVNULL,
                       stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
    ran = re.search(r"^Ran (\d+) tests?", r.stdout, re.M)
    end = re.search(r"^(OK|FAILED)\b.*$", r.stdout, re.M)
    outcome = end.group(0) if end and r.returncode in (0, 1) else f"FAILED (exit {r.returncode})"
    if r.returncode != 0 and outcome.startswith("OK"):
        outcome = f"FAILED (exit {r.returncode})"
    return unit, int(ran.group(1)) if ran else 0, outcome, r.stdout, time.monotonic() - t


def main() -> int:
    ap = argparse.ArgumentParser(prog="ci/suite", description=__doc__.split("\n\n")[0])
    ap.add_argument("-j", type=int, default=min(16, 2 * len(os.sched_getaffinity(0))), help="classes at a time")
    ap.add_argument("only", nargs="*", metavar="CLASS", help="run these classes (module.Class) and no other")
    a = ap.parse_args()
    found = classes()
    units = sorted(a.only or found, key=lambda u: -found.get(u, 0))
    t = time.monotonic()
    ran, failed, skipped, took = 0, [], 0, []
    with ThreadPoolExecutor(max_workers=a.j) as pool:
        for done in as_completed([pool.submit(run, u) for u in units]):
            unit, n, outcome, out, secs = done.result()
            ran += n
            took.append((secs, unit))
            skipped += sum(int(k) for k in re.findall(r"skipped=(\d+)", outcome))
            if not outcome.startswith("OK"):
                failed.append(unit)
                print(f"{'=' * 70}\n{unit}: {outcome}\n{out.rstrip()}", file=sys.stderr, flush=True)
    slow = ", ".join(f"{u} {s:.0f}s" for s, u in sorted(took, reverse=True)[:3])
    print(f"\nRan {ran} tests in {len(units)} classes in {time.monotonic() - t:.1f}s, {a.j} at a time "
          f"(longest: {slow})\n", file=sys.stderr)
    tail = f" (skipped={skipped})" if skipped else ""
    print(f"FAILED (classes={len(failed)}){tail}: {' '.join(failed)}" if failed else f"OK{tail}", file=sys.stderr)
    return 1 if failed else 0


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