<?php
declare(strict_types=1);

$root = dirname(__DIR__);
$strict = in_array('--strict', $argv, true);
$mysqlRequired = [
    'tests/Admin/task15.php',
    'tests/Admin/task84.php',
    'tests/Api/task8.php',
    'tests/Api/task80.php',
    'tests/Database/task3.php',
    'tests/Install/task9.php',
    'tests/Questions/task5.php',
    'tests/Security/task4.php',
    'tests/Community/task86.php',
];
$files = [];
$testsPath = $root . '/tests';
if (!is_dir($testsPath)) {
    fwrite(STDERR, "Tests are not bundled in this distribution package.\n");
    exit(2);
}
$dir = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($testsPath, FilesystemIterator::SKIP_DOTS));
foreach ($dir as $file) {
    if ($file->isFile() && (preg_match('/task\d+\.php$/', $file->getFilename()) || str_ends_with($file->getFilename(), 'Regression.php'))) {
        $files[] = $file->getPathname();
    }
}
sort($files, SORT_STRING);

$passed = 0;
$skipped = 0;
$failed = 0;
$skippedList = [];
$failedList = [];

echo "Running " . count($files) . " task tests...\n";
foreach ($files as $file) {
    $rel = str_replace($root . DIRECTORY_SEPARATOR, '', $file);
    if (!extension_loaded('pdo_mysql') && in_array(str_replace('\\', '/', $rel), $mysqlRequired, true)) {
        $skipped++;
        $skippedList[] = $rel;
        echo "SKIP: {$rel} (PDO MySQL not loaded)\n";
        continue;
    }

    $cmd = 'php ' . escapeshellarg($file);
    $output = [];
    $code = 0;
    exec($cmd . ' 2>&1', $output, $code);
    if ($code === 0) {
        $passed++;
        echo "PASS: {$rel}\n";
        continue;
    }

    if ($code === 2) {
        $skipped++;
        $skippedList[] = $rel;
        echo "SKIP: {$rel}\n";
        if ($output !== []) {
            echo "   --> " . implode("\n   --> ", array_slice($output, -5)) . "\n";
        }
        continue;
    }

    $failed++;
    echo "FAIL: {$rel}\n";
    echo "   --> " . implode("\n   --> ", array_slice($output, -10)) . "\n";
    $failedList[] = $rel;
}

echo "\nSummary: {$passed} passed, {$skipped} skipped, {$failed} failed out of " . count($files) . " tests.\n";
if ($skipped > 0) {
    echo "Skipped:\n- " . implode("\n- ", $skippedList) . "\n";
}
if ($failed > 0) {
    echo "Failures:\n- " . implode("\n- ", $failedList) . "\n";
    exit(1);
}
if ($strict && $skipped > 0) {
    fwrite(STDERR, "Strict mode requires zero skipped tests.\n");
    exit(1);
}
exit(0);
