# 先校验生成物，避免将过期清单带入提交
echo "🔍 Checking plugin manifests..."
pnpm run manifests:check || exit 1

# 生成输入和投影物都必须与索引一致，避免提交旧源文件与新投影物。
# 引用 pathspec 交给 Git 匹配，不能由 shell 展开，否则会漏掉已删除的文件。
set -- \
  'plugins/*/src/manifest.ts' \
  'plugins/manifest.types.ts' \
  'scripts/buildPluginManifests.ts' \
  'scripts/pluginDiscovery.ts' \
  'plugins/*/dsh.plugin.json' \
  'plugins/*/.env.example'
if ! git diff --quiet -- "$@"; then
  echo "❌ 插件清单生成输入或投影物有未暂存改动："
  git diff --name-only -- "$@"
  echo "   运行 pnpm run manifests 后重新 git add 相关输入与投影物。"
  exit 1
fi
UNTRACKED_MANIFEST_FILES=$(git ls-files --others --exclude-standard -- "$@")
if [ -n "$UNTRACKED_MANIFEST_FILES" ]; then
  echo "❌ 插件清单生成输入或投影物未跟踪："
  echo "$UNTRACKED_MANIFEST_FILES"
  echo "   运行 pnpm run manifests 后 git add 相关输入与投影物。"
  exit 1
fi

# 提交前自动格式化，并把已暂存文件的最新格式重新写入暂存区
echo "🧹 Formatting code..."
pnpm run fmt
git update-index --again

# 检查代码质量
echo "🔍 Running linter..."
pnpm run lint
if [ $? -ne 0 ]; then
  echo "❌ Lint check failed. Please run 'pnpm run lint:fix' to fix linting issues."
  exit 1
fi

# 运行测试（vitest 在 TTY 下默认 watch 模式，必须显式 --run，否则提交会挂住）
echo "🧪 Running tests..."
pnpm run test:run
