#!/usr/bin/env sh
# . "$(dirname -- "$0")/_/husky.sh"
# 先校验；无问题则直接提交；有问题则修复后再次校验，通过则提交

# 带 loading 旋转图标的执行： run_with_spinner "提示文案" 命令...
run_with_spinner() {
  msg="$1"
  shift
  "$@" &
  pid=$!
  i=0
  while kill -0 $pid 2>/dev/null; do
    case $i in 0) c='|';; 1) c='/';; 2) c='-';; 3) c='\';; *) i=0; c='|';; esac
    printf '\r  %s %s' "$c" "$msg"
    i=$((i + 1))
    [ $i -ge 4 ] && i=0
    sleep 0.15
  done
  wait $pid
  ret=$?
  printf '\r'
  return $ret
}

echo "🔍 开始校验代码..."
if run_with_spinner "校验中..." sh -c 'pnpm run lint 2>/dev/null'; then
  echo "✅ 校验通过，开始提交"
  exit 0
fi

echo "⚠️  存在需修复项，开始自动修复..."
staged_files=$(git diff --cached --name-only --diff-filter=ACM)
run_with_spinner "自动修复中..." pnpm run lint:fix
if [ -n "$staged_files" ]; then
  echo "$staged_files" | xargs git add
fi

echo "🔍 修复完成，再次校验..."
run_with_spinner "校验中..." pnpm run lint
echo "✅ 校验通过，开始提交"
