#!/usr/bin/env bash

## Description: Run PHPUnit with code coverage (pcov) and print per-module totals
## Usage: phpunit-coverage [path] [phpunit flags]
## Example: "ddev phpunit-coverage" or "ddev phpunit-coverage modules/flowdrop_memory" or "ddev phpunit-coverage --filter testFoo"
## ExecRaw: true

set -eu -o pipefail

# Coverage runs are serial (plain PHPUnit against phpunit.xml, not the
# run-tests.sh wrapper phpunit-parallel uses) — an accepted cost for an
# occasional metrics run. Defaults to the flowdrop-unit-kernel testsuite:
# Functional tests execute code in separate HTTP requests the collector
# cannot see, so they add runtime without adding coverage.
#
# Reports land in coverage/ (gitignored): html/index.html, clover.xml,
# coverage.txt. scripts/coverage-report.php then prints three tables:
# by architectural role (logic vs boilerplate — the actionable view),
# top gaps in logic code, and the blended per-module totals.

if ! command -v phpunit >/dev/null; then
  echo "phpunit is not available. You may need to 'ddev composer install'" >&2
  exit 1
fi

if ! php -m | grep -qi '^pcov$'; then
  echo "The pcov extension is not installed. Run 'ddev restart' once so" >&2
  echo ".ddev/config.coverage.yaml can install php8.4-pcov, then retry." >&2
  exit 1
fi

OUT="coverage"
ARGS=("$@")

# Unless the caller picked a target (a path, --testsuite, or --filter),
# default to the Unit+Kernel suite.
TARGETED=0
for arg in "${ARGS[@]:-}"; do
  case "$arg" in
    --testsuite*|--filter*) TARGETED=1 ;;
    -*) ;;
    *) [ -e "$arg" ] && TARGETED=1 ;;
  esac
done
if [ "$TARGETED" -eq 0 ]; then
  ARGS+=(--testsuite flowdrop-unit-kernel)
fi

mkdir -p "$OUT"

php \
  -d pcov.enabled=1 \
  -d pcov.directory="$PWD" \
  -d 'pcov.exclude=~/(vendor|web|node_modules)/~' \
  -d memory_limit=-1 \
  "$(command -v phpunit)" \
  --coverage-html "$OUT/html" \
  --coverage-clover "$OUT/clover.xml" \
  --coverage-text="$OUT/coverage.txt" \
  "${ARGS[@]}"

echo
php scripts/coverage-report.php "$OUT/clover.xml" "$OUT/roles.html"
echo
echo "HTML reports: $OUT/roles.html (by role) · $OUT/html/index.html (per file)"
