#!/usr/bin/env php
<?php

declare(strict_types=1);

/**
 * Fail CI when line coverage falls below the configured floor.
 * Usage: php tests/check-coverage.php [minPercent]
 */

$min = isset($argv[1]) ? (float)$argv[1] : 40.0;
$root = dirname(__DIR__);

$envPrefix = '';
if (extension_loaded('xdebug') && !extension_loaded('pcov')) {
    // Xdebug 3 defaults to develop mode; PHPUnit needs coverage mode.
    $envPrefix = 'XDEBUG_MODE=coverage ';
}

$cmd = sprintf(
    '%s%s %s/vendor/bin/phpunit --coverage-text --colors=never 2>&1',
    $envPrefix,
    escapeshellarg(PHP_BINARY),
    escapeshellarg($root)
);

$output = [];
exec($cmd, $output, $exitCode);
echo implode("\n", $output) . "\n";

if ($exitCode !== 0) {
    exit($exitCode);
}

$linesPct = null;
foreach ($output as $line) {
    // PHPUnit 11 / Xdebug: "Lines:   25.33% (1484/5859)"
    if (preg_match('/^\s*Lines:\s+([\d.]+)%\s+\(/', $line, $m)) {
        $linesPct = (float)$m[1];
        break;
    }
    // PCOV / older format: "Lines:   1484/5859 (25.33%)"
    if (preg_match('/^\s*Lines:\s+[\d.]+\/\d+\s+\(\s*([\d.]+)%/', $line, $m)) {
        $linesPct = (float)$m[1];
        break;
    }
}

if ($linesPct === null) {
    fwrite(STDERR, "Could not parse coverage summary. Is PCOV or Xdebug enabled?\n");
    exit(1);
}

if ($linesPct < $min) {
    fwrite(STDERR, sprintf("Line coverage %.2f%% is below minimum %.2f%%\n", $linesPct, $min));
    exit(1);
}

fwrite(STDERR, sprintf("Line coverage %.2f%% meets minimum %.2f%%\n", $linesPct, $min));
exit(0);
