#!/bin/sh
set -e

ROOT="$(git rev-parse --show-toplevel)"
TMP_DIR="$ROOT/.poratake-fast-check.$$"
FAILED=0

cleanup() {
  rm -rf "$TMP_DIR"
}
trap cleanup EXIT

MATCHED=0
set --
IFS='
'
for FILE in $(git diff --cached --name-only --diff-filter=ACMR); do
  case "$FILE" in
    vendor/*) continue ;;
    *.ts | *.mjs | *.json | *.md) ;;
    *) continue ;;
  esac

  MATCHED=1
  TMP_FILE="$TMP_DIR/$FILE"
  mkdir -p "$(dirname "$TMP_FILE")"
  git show ":$FILE" | sed 's/\r$//' > "$TMP_FILE"
  set -- "$@" "$TMP_FILE"
done

if [ "$MATCHED" -eq 1 ]; then
  if ! bunx oxfmt --check "$@" > /dev/null 2>&1; then
    echo "oxfmt: staged files are not formatted. Run: bunx oxfmt <files>"
    FAILED=1
  fi

  if ! bunx oxlint "$@" --deny-warnings --no-error-on-unmatched-pattern > /dev/null 2>&1; then
    echo "oxlint: staged files have lint errors. Run: bunx oxlint <files>"
    FAILED=1
  fi
fi

if ! (cd "$ROOT" && bun run check:daemon-contract > /dev/null 2>&1); then
  echo "Generated daemon contract is stale. Run: bun run check:daemon-contract"
  FAILED=1
fi

exit $FAILED
