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

# Worktrees can share this hook through an absolute core.hooksPath, and an older
# worktree may lack the script, so run the copy beside this hook.
size_check="$(dirname "$0")/../scripts/check-staged-size.mjs"

if ! command -v bun >/dev/null 2>&1; then
  echo "bun is required to format staged files before commit." >&2
  exit 1
fi

files=()
while IFS= read -r -d '' file; do
  # oxfmt follows symbolic links and would format the link target, which may
  # be an ignored file. Their contents are formatted through their canonical
  # targets instead.
  if [ -L "$file" ]; then
    continue
  fi
  case "$file" in
    dist_*|dist_*/*|output|output/*|node_modules|node_modules/*) continue ;;
    *.ts|*.tsx|*.js|*.jsx|*.json|*.css|*.md|*.html|*.yml|*.yaml) files+=("$file") ;;
  esac
done < <(git diff --cached --name-only --diff-filter=ACMR -z)

if [ "${#files[@]}" -eq 0 ]; then
  exec node "$size_check"
fi

dirty=()
for file in "${files[@]}"; do
  if ! git diff --quiet -- "$file"; then
    dirty+=("$file")
  fi
done

if [ "${#dirty[@]}" -ne 0 ]; then
  echo "Cannot safely format staged files with unstaged edits:" >&2
  printf '  %s\n' "${dirty[@]}" >&2
  echo "Stage or stash those edits first, then commit again." >&2
  exit 1
fi

bun x oxfmt --no-error-on-unmatched-pattern "${files[@]}"
git add -- "${files[@]}"
git diff --cached --check

# Measured after formatting, which can change the staged size.
node "$size_check"
