#!/bin/sh

# Get list of staged files before running checks
STAGED_FILES=$(git diff --cached --name-only)

if [ -z "$STAGED_FILES" ]; then
  echo "No staged files to check."
  exit 0
fi

echo "Running checks on staged files..."

run_checks() {
  # shellcheck disable=SC2086 # intentionally preserving word splitting for file list
  CHECK_OUTPUT=""
  CHECK_STATUS=0
  set +e
  CHECK_OUTPUT="$(npx -y @biomejs/biome check --write --error-on-warnings "$1" 2>&1)"
  CHECK_STATUS=$?
  set -e

  if [ "$CHECK_STATUS" -ne 0 ]; then
    if printf '%s\n' "$CHECK_OUTPUT" | grep -Fq "No files were processed in the specified paths."; then
      return 0
    fi
    echo "$CHECK_OUTPUT"
    return "$CHECK_STATUS"
  fi

  [ -n "$CHECK_OUTPUT" ] && echo "$CHECK_OUTPUT"
}

# Run Biome only when staged files include style targets
if echo "$STAGED_FILES" | grep -Eq '\.(ts|tsx|js|jsx|json)$'; then
  echo "Running biome on staged files..."
  TS_OR_JS_FILES=$(echo "$STAGED_FILES" | grep -E '\.(ts|tsx|js|jsx|json)$' | tr '\n' ' ')
  if [ -n "$TS_OR_JS_FILES" ]; then
    run_checks "$TS_OR_JS_FILES"
  fi
fi

RUN_BROWSER_SMOKE=0
for file in $STAGED_FILES; do
  case "$file" in
    packages/ai/*|package.json|package-lock.json)
      RUN_BROWSER_SMOKE=1
      break
      ;;
  esac
done

if [ $RUN_BROWSER_SMOKE -eq 1 ]; then
  echo "Running browser smoke check..."
  npm run check:browser-smoke
  if [ $? -ne 0 ]; then
    echo "❌ Browser smoke check failed."
    exit 1
  fi
fi

# Restage files that were previously staged and may have been modified by formatting
for file in $STAGED_FILES; do
  if [ -f "$file" ]; then
    git add "$file"
  fi
done

echo "✅ All pre-commit checks passed!"
