#!/usr/bin/env bash
set -euo pipefail

SOFT_CAP=${SOFT_CAP:-400}
HARD_CAP=${HARD_CAP:-650}
warn=0
fail=0
ALLOW_FILE=${SIZE_ALLOWLIST:-.size-limits.allow}

is_allowed() {
  local file=$1
  [[ -f "$ALLOW_FILE" ]] && grep -Fxq "$file" "$ALLOW_FILE"
}

while IFS= read -r file; do
  lines=$(wc -l <"$file")
  if (( lines > HARD_CAP )); then
    if is_allowed "$file"; then
      printf 'ALLOW (hard cap): %s has %d lines (hard cap %d)\n' "$file" "$lines" "$HARD_CAP"
      warn=1
      continue
    fi
    printf 'FAIL: %s has %d lines (hard cap %d)\n' "$file" "$lines" "$HARD_CAP"
    fail=1
  elif (( lines > SOFT_CAP )); then
    printf 'WARN: %s has %d lines (soft cap %d)\n' "$file" "$lines" "$SOFT_CAP"
    warn=1
  fi
done < <(git ls-files '*.rs')

if (( fail == 1 )); then
  echo "One or more Rust files exceed the hard cap. Please split them before merging."
  exit 1
fi

if (( warn == 1 )); then
  echo "Warnings emitted for files exceeding the soft cap. Consider splitting them."
fi
