#!/usr/bin/env bash
# StoryFab pre-commit hook
#
# 安装方法 (手动):
#   cp scripts/hooks/pre-commit .git/hooks/pre-commit
#   chmod +x .git/hooks/pre-commit
#
# 自动安装:
#   bash scripts/install-hooks.sh
#
# 约束来源: ADR-006 (本地禁打 tag + 强制全局账户) + ADR-002 (禁 antd)

set -e

REPO_ROOT="$(git rev-parse --show-toplevel)"
cd "$REPO_ROOT"

echo "🛡️  StoryFab pre-commit checks..."

# 1. 校验禁止打 tag
if [ -f scripts/verify-no-tag.mjs ]; then
  node scripts/verify-no-tag.mjs || exit 1
fi

# 2. 校验禁用 antd
if [ -f scripts/check-antd.mjs ]; then
  node scripts/check-antd.mjs || exit 1
fi

# 3. 校验暂存文件无 AI byline
STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACMR | grep -E '\.(md|ts|tsx|js|jsx|json|yml|yaml|toml|css|scss|less|html)$' || true)
if [ -n "$STAGED_FILES" ]; then
  AI_BYLINE_FOUND=$(echo "$STAGED_FILES" | xargs grep -lE "🤖|Generated with \[Claude Code\]|anthropic\.com|Co-Authored-By:.*Claude|Co-Authored-By:.*Hermes" 2>/dev/null || true)
  if [ -n "$AI_BYLINE_FOUND" ]; then
    echo "❌ 检测到 AI byline 残留:" >&2
    echo "$AI_BYLINE_FOUND" | sed 's/^/  /' >&2
    echo "" >&2
    echo "请移除 Co-Authored-By / 🤖 / anthropic.com 等标记" >&2
    exit 1
  fi
fi

# 4. 检测暂存文件含 .ts/.tsx 改动时跑 tsc (仅增量)
TS_CHANGED=$(git diff --cached --name-only --diff-filter=ACMR | grep -E '\.(ts|tsx)$' | head -3 || true)
if [ -n "$TS_CHANGED" ]; then
  echo "📝 TypeScript 改动检测到，建议本地跑: pnpm type-check"
fi

echo "✅ pre-commit checks 通过"
