<?php
// tests/run.php — Test runner: PASS/FAIL per assertion, exit 1 on any failure
// Usage: php tests/run.php [TEST_BASE_URL=http://...] [TEST_SESSION_COOKIE=PHPSESSID=...]

if (php_sapi_name() !== 'cli') {
    http_response_code(403);
    exit('Tests only run from CLI.');
}

// Parse env overrides from argv
foreach (array_slice($argv ?? [], 1) as $arg) {
    if (strpos($arg, '=') !== false) {
        [$k, $v] = explode('=', $arg, 2);
        define($k, $v);
    }
}
if (!defined('TEST_BASE_URL'))       define('TEST_BASE_URL', 'https://dimark.co/supercerebro');
if (!defined('TEST_SESSION_COOKIE')) define('TEST_SESSION_COOKIE', '');

$GLOBALS['_dm_pass']  = 0;
$GLOBALS['_dm_fail']  = 0;
$GLOBALS['_dm_skip']  = 0;

function dm_assert(string $label, bool $cond, string $detail = ''): void {
    if ($cond) {
        echo "\033[32m  PASS\033[0m  {$label}\n";
        $GLOBALS['_dm_pass']++;
    } else {
        echo "\033[31m  FAIL\033[0m  {$label}" . ($detail ? " — {$detail}" : '') . "\n";
        $GLOBALS['_dm_fail']++;
    }
}

function dm_skip(string $label, string $reason = ''): void {
    echo "\033[33m  SKIP\033[0m  {$label}" . ($reason ? " — {$reason}" : '') . "\n";
    $GLOBALS['_dm_skip']++;
}

// Run all test files
$tests = glob(__DIR__ . '/test-*.php') ?: [];
echo "SuperCerebro test suite — " . count($tests) . " file(s)\n";
echo "Base URL : " . TEST_BASE_URL . "\n";
echo "Session  : " . (TEST_SESSION_COOKIE ? 'set' : 'not set (authenticated tests will be skipped)') . "\n";

foreach ($tests as $file) {
    echo "\n--- " . basename($file) . " ---\n";
    require $file;
}

// Summary
$pass = $GLOBALS['_dm_pass'];
$fail = $GLOBALS['_dm_fail'];
$skip = $GLOBALS['_dm_skip'];
$color = $fail > 0 ? "\033[31m" : "\033[32m";
echo "\n{$color}=== Results: {$pass} passed, {$fail} failed, {$skip} skipped ===\033[0m\n";

exit($fail > 0 ? 1 : 0);
