#!/usr/bin/env bash
#
# Fail if the PHPStan baseline suppresses any production (non-test) code.
#
# The baseline is allowed to hold test-only entries (Prophecy/PHPUnit mock
# patterns PHPStan cannot resolve), but production suppressions must be fixed
# at the source, not baselined. This gate keeps the production baseline at zero
# so new production suppressions are caught in review instead of accumulating.
#
# Usage: scripts/phpstan-no-prod-suppressions.sh [path-to-baseline]

set -eu -o pipefail

BASELINE="${1:-phpstan-baseline.neon}"

if [ ! -f "$BASELINE" ]; then
  echo "No baseline found at '$BASELINE' — nothing to check."
  exit 0
fi

# Collect every suppressed path that is not under a tests/ directory.
# POSIX [[:space:]] keeps this portable across GNU and BSD grep/sed.
prod_paths="$(grep -E '^[[:space:]]*path:' "$BASELINE" \
  | sed -E 's/^[[:space:]]*path:[[:space:]]*//' \
  | grep -vE '(^|/)tests/' \
  | sort -u || true)"

if [ -n "$prod_paths" ]; then
  count="$(printf '%s\n' "$prod_paths" | wc -l | tr -d ' ')"
  echo "ERROR: $count production file(s) are suppressed in $BASELINE."
  echo "Fix these at the source (type guards / narrowing) instead of baselining:"
  echo
  printf '%s\n' "$prod_paths" | sed 's/^/  - /'
  echo
  echo "The production baseline must stay at zero. Only test-only entries are allowed."
  exit 1
fi

echo "OK: no production suppressions in $BASELINE."
