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

declare(strict_types=1);

/**
 * Fails when the line coverage of a Clover report falls under the floors below.
 *
 * Usage: bin/check-coverage var/clover.xml (composer test:coverage produces the report and runs this).
 *
 * The floors are the measured coverage rounded down (2026-11-04: 95.2 % overall, after the milestone of tests that came with the audit; it was 93.4 %). Raise them when the
 * coverage rises; never lower one to let a change through, write the missing test instead.
 */
const FLOORS = [
    // Overall, every file of src/.
    '*' => 95.0,
    // The directories a mistake costs the most in: access, tenancy, authentication, the data layer.
    'Auth' => 96.0,
    'Doctrine' => 95.0,
    'Entity' => 95.0,
    'Http' => 100.0,
    'Security' => 95.0,
    'Serializer' => 100.0,
    'State' => 94.0,
    'Tenant' => 98.0,
];

$report = $argv[1] ?? 'var/clover.xml';
if (!is_file($report)) {
    fwrite(STDERR, sprintf("No coverage report at %s: run composer test:coverage.\n", $report));
    exit(2);
}

$xml = simplexml_load_file($report);
if (false === $xml) {
    fwrite(STDERR, sprintf("%s is not a Clover report.\n", $report));
    exit(2);
}

/** @var array<string, array{covered: int, total: int}> $directories */
$directories = ['*' => ['covered' => 0, 'total' => 0]];
foreach ($xml->xpath('//file') ?: [] as $file) {
    $metrics = $file->metrics;
    if (!isset($metrics['statements'])) {
        continue;
    }

    $path = (string) $file['name'];
    $relative = substr($path, (int) strrpos($path, '/src/') + 5);
    $directory = str_contains($relative, '/') ? strstr($relative, '/', true) : '(root)';

    foreach (['*', $directory] as $key) {
        $directories[$key] ??= ['covered' => 0, 'total' => 0];
        $directories[$key]['covered'] += (int) $metrics['coveredstatements'];
        $directories[$key]['total'] += (int) $metrics['statements'];
    }
}

$failures = 0;
foreach (FLOORS as $directory => $floor) {
    $measured = $directories[$directory] ?? ['covered' => 0, 'total' => 0];
    $percent = $measured['total'] > 0 ? 100 * $measured['covered'] / $measured['total'] : 0.0;
    $ok = $percent >= $floor;
    $failures += $ok ? 0 : 1;

    printf("%s %-12s %5.1f %% (floor %5.1f %%, %d/%d statements)\n", $ok ? 'ok  ' : 'FAIL', '*' === $directory ? 'overall' : $directory, $percent, $floor, $measured['covered'], $measured['total']);
}

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