#!/usr/bin/env php
<?php
/*
 * Test ratchet: the list of known failing tests can only get shorter.
 *
 * Usage:
 *   scripts/test-ratchet                       # run the Feature, Unit, and Golden suites, then check the result
 *   scripts/test-ratchet --junit <file>        # check an existing JUnit file (CI)
 *   scripts/test-ratchet --junit <a> --junit <b>     # check the JUnit files of all shards of one run together
 *   scripts/test-ratchet --update [--junit <file>]   # rewrite the list with the failures of the run
 *
 * Options:
 *   --list <file>       the list of known failures (default: tests/known-failures.txt)
 *   --exit-code <code>  the exit code of the test run; a failed run without failed tests in the
 *                       JUnit file (a crash) fails the check
 *
 * The check fails when:
 *   - a test fails that is not in the list (a new failure: fix it),
 *   - a listed test passes or is not in the run (remove its line from the list),
 *   - a test file under tests/Feature or tests/Unit has no result (a crashed worker).
 * Each line of the list is <test file>::<test name>, with the file taken from the JUnit class
 * (Tests\Unit\FooTest is tests/Unit/FooTest.php) and the name as Pest or PHPUnit reports it.
 * A line that starts with `[flaky] ` marks a test that fails only sometimes: it can fail or pass.
 * Quarantine a test this way only after you reproduce the flake, and name the cause in a comment.
 * --update keeps comments and flaky lines and replaces all other lines.
 *
 * Merge order: the list is generated from a full run. When two branches change failing tests
 * (for example one fixes tests while another adds the ratchet or breaks a known test), the branch
 * that merges second must rebase, run `scripts/test-ratchet --update`, and commit the new list.
 * Review the diff of the list: --update can add new failures, and only removed lines are normal.
 * The CI shard jobs upload their JUnit files as the `junit-php-shard-1` to `junit-php-shard-3` artifacts.
 * To take the list from a CI run:
 *   scripts/test-ratchet --update --junit <shard 1 junit.xml> --junit <shard 2 junit.xml> --junit <shard 3 junit.xml>
 * Local runs need the Vite manifest (npm ci && npm run build), like the CI job.
 */

$root = dirname(__DIR__);
$options = getopt('', ['junit:', 'list:', 'exit-code:', 'update', 'help']);

if (isset($options['help'])) {
    preg_match('#/\*(.*?)\*/#s', file_get_contents(__FILE__), $match);
    echo preg_replace('/^ \* ?/m', '', trim($match[1])), "\n";
    exit(0);
}

$listFile = $options['list'] ?? "$root/tests/known-failures.txt";
$junitFiles = (array) ($options['junit'] ?? []);
$exitCode = isset($options['exit-code']) ? (int) $options['exit-code'] : null;

if ($junitFiles === []) {
    if (! is_file("$root/public/build/manifest.json")) {
        fail('public/build/manifest.json does not exist. Run `npm ci && npm run build` first; page tests need the Vite manifest.');
    }
    $junitFile = "$root/storage/framework/testing/junit.xml";
    @unlink($junitFile);
    $command = 'php artisan test --compact --parallel --testsuite=Feature,Unit,Golden --log-junit '.escapeshellarg($junitFile);
    echo "$command\n";
    $started = time();
    passthru('cd '.escapeshellarg($root).' && '.$command, $exitCode);
    echo 'Suite wall time: '.(time() - $started)." s\n";
    $junitFiles = [$junitFile];
}

/** @var array<string, string> $failed id => first line of the message */
$failed = [];
/** @var array<string, true> $seen */
$seen = [];
/** @var array<string, true> $ranFiles */
$ranFiles = [];
$cases = [];
foreach ($junitFiles as $junitFile) {
    if (! is_file($junitFile)) {
        fail("The JUnit file $junitFile does not exist. The test run did not finish.");
    }
    $xml = @simplexml_load_file($junitFile);
    if ($xml === false) {
        fail("The JUnit file $junitFile is not valid XML. The test run did not finish.");
    }
    array_push($cases, ...$xml->xpath('//testcase'));
}
foreach ($cases as $case) {
    // Pest and PHPUnit both name the class after the file (PSR-4): Tests\Unit\FooTest is tests/Unit/FooTest.php.
    $file = str_replace('\\', '/', lcfirst((string) $case['class'])).'.php';
    $name = (string) $case['name'];
    $id = "$file::$name";
    $seen[$id] = true;
    $ranFiles[$file] = true;
    $problem = $case->failure[0] ?? $case->error[0] ?? null;
    if ($problem !== null) {
        $message = trim((string) $problem);
        $message = str_starts_with($message, $name) ? substr($message, strlen($name)) : $message;
        $failed[$id] = strtok($message, "\n") ?: (string) $problem['type'];
    }
}

if ($seen === []) {
    fail('The JUnit files have no test cases.');
}
if ($exitCode !== null && $exitCode !== 0 && $failed === []) {
    fail("The test run exited with code $exitCode, but the JUnit file has no failed test. The run crashed.");
}

// A crashed parallel worker drops the files it had not run yet, so a run must contain every test file.
$notRun = [];
foreach (['Feature', 'Unit'] as $suite) {
    $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator("$root/tests/$suite", FilesystemIterator::SKIP_DOTS));
    foreach ($files as $path) {
        $file = relative((string) $path, $root);
        if (str_ends_with($file, 'Test.php') && ! isset($ranFiles[$file])
            && preg_match('/^\s*(test|it|describe)\(|function test\w*\(|#\[Test\]/m', file_get_contents((string) $path))) {
            $notRun[] = $file;
        }
    }
}
if ($notRun !== []) {
    sort($notRun);
    fail(count($notRun)." test files did not run, probably a crashed worker. First: {$notRun[0]}. Read the test output.");
}

/** @var array<string, true> $known */
$known = [];
/** @var array<string, true> $flaky */
$flaky = [];
/** @var list<string> $kept comment and flaky lines that --update keeps */
$kept = [];
if (is_file($listFile)) {
    foreach (file($listFile, FILE_IGNORE_NEW_LINES) as $line) {
        if (str_starts_with($line, '[flaky] ')) {
            $flaky[substr($line, 8)] = true;
            $kept[] = $line;
        } elseif (str_starts_with($line, '#')) {
            $kept[] = $line;
        } elseif (trim($line) !== '') {
            $known[$line] = true;
        }
    }
}

if (isset($options['update'])) {
    $ids = array_keys(array_diff_key($failed, $flaky));
    sort($ids, SORT_STRING);
    $header = $kept === [] ? [
        '# Known failing tests. The test ratchet (scripts/test-ratchet) fails when a test fails that is',
        '# not in this list, and when a listed test passes. Remove a line when you fix its test.',
        '# Regenerate with: scripts/test-ratchet --update (see scripts/test-ratchet --help)',
    ] : $kept;
    file_put_contents($listFile, implode("\n", [...$header, ...$ids])."\n");
    printf("test-ratchet: wrote %d known failures from %d tests to %s\n", count($ids), count($seen), relative($listFile, $root));
    exit(0);
}

$new = array_diff_key($failed, $known, $flaky);
$fixed = array_keys(array_diff_key(array_intersect_key($known, $seen), $failed));
$missing = array_keys(array_diff_key($known + $flaky, $seen));
$list = relative($listFile, $root);

foreach ($new as $id => $message) {
    echo "NEW FAILURE  $id\n             $message\n";
}
foreach ($fixed as $id) {
    echo "NOW PASSES   $id\n             Remove this line from $list.\n";
}
foreach ($missing as $id) {
    echo "NOT IN RUN   $id\n             The test was renamed or deleted. Remove this line from $list.\n";
}

$ok = $new === [] && $fixed === [] && $missing === [];
printf(
    "test-ratchet: %s - %d tests, %d failed (%d known, %d flaky), %d new failures, %d known now pass, %d listed not in run\n",
    $ok ? 'OK' : 'FAILED', count($seen), count($failed), count(array_intersect_key($failed, $known)),
    count(array_intersect_key($failed, $flaky)), count($new), count($fixed), count($missing),
);
exit($ok ? 0 : 1);

function fail(string $message): never
{
    fwrite(STDERR, "test-ratchet: FAILED - $message\n");
    exit(1);
}

function relative(string $path, string $root): string
{
    return str_starts_with($path, "$root/") ? substr($path, strlen($root) + 1) : $path;
}
