#!/bin/bash
# Git pre-commit hook:
# 1. Block direct commits on protected mainline branches (main/master).
# 2. Enforce the device branch-prefix rule (.agents/rules/branch-naming.md)
#    and strictly lowercase branch names (.agents/rules/windows-development.md)
#    via .githooks/branch-guard.sh.
# 3. Intercept staged files exceeding 15MB or violating Windows filename safety
#    (illegal characters : * ? " < > | and system reserved device names).
# 4. Route staged governance documents to their dedicated checkers:
#      AGENTS.md, .agents/rules/*.md   -> bun run verify:agents-md
#      SKILL.md, skills references     -> bun run verify:skill-md
#    Local gates fail open when bun is unavailable; CI re-runs both.

source "$(dirname "$0")/branch-guard.sh"

current_branch="$(git branch --show-current)"

# 1. 拦截受保护的主干分支直接提交
if [ "$current_branch" = "main" ] || [ "$current_branch" = "master" ]; then
  if [ "$ALLOW_MAIN_COMMIT" != "1" ]; then
    echo "" >&2
    echo "======================================================================" >&2
    echo "❌ [Git Hook 拦截] 严禁直接在主分支 ($current_branch) 上进行 commit！" >&2
    echo "======================================================================" >&2
    echo "📌 团队协作规范：" >&2
    echo "   1. 主分支受保护，禁止直接开发与提交代码。" >&2
    echo "   2. 所有新功能与 Bug 修复必须在特性分支（如 mac15/your-feature-name）进行。" >&2
    echo "   3. 代码合并必须通过 GitHub Pull Request (PR) 经由审查后在远端合入。" >&2
    echo "" >&2
    echo "💡 快速解决指引：" >&2
    echo "   创建并切换到新特性分支（工作区现有改动会自动带入）：" >&2
    echo "     git switch -c mac15/your-feature-name" >&2
    echo "   然后重新执行 git commit 即可。" >&2
    echo "   (紧急一次性旁路: ALLOW_MAIN_COMMIT=1 git commit ...)" >&2
    echo "======================================================================" >&2
    echo "" >&2
    exit 1
  fi
fi

# 2. 分支命名与小写校验
guard_branch_name "$current_branch" || exit 1

# 3. 校验暂存区文件（文件体积与 Windows 文件名合规性）
MAX_FILE_SIZE=15728640  # 15MB in bytes
staged_check_files="$(git diff --cached --name-only --diff-filter=ACM)"

if [ -n "$staged_check_files" ]; then
  OLD_IFS="$IFS"
  IFS='
'
  for file in $staged_check_files; do
    # 3.1 校验单文件体积上限 (15MB)
    if [ -f "$file" ]; then
      file_size=$(wc -c < "$file" 2>/dev/null | tr -d ' ')
      if [ -n "$file_size" ] && [ "$file_size" -gt "$MAX_FILE_SIZE" ]; then
        size_mb=$(awk "BEGIN {printf \"%.2f\", $file_size/1048576}")
        echo "" >&2
        echo "======================================================================" >&2
        echo "❌ [Git Hook 拦截] 暂存区存在超过 15MB 的超大文件！" >&2
        echo "======================================================================" >&2
        echo "📌 违规文件: $file (${size_mb} MB > 15 MB)" >&2
        echo "📌 规范说明：为避免仓库体积永久膨胀，严禁在源码仓库中提交超大文件。" >&2
        echo "💡 解决办法：" >&2
        echo "   1. 将大文件移出代码仓库，并在 .gitignore 中声明忽略；" >&2
        echo "   2. 安装包或可执行二进制产物请通过 GitHub Releases 附件发布。" >&2
        echo "======================================================================" >&2
        echo "" >&2
        IFS="$OLD_IFS"
        exit 1
      fi
    fi

    # 3.2 校验 Windows 文件名合法性（字符与设备保留字）
    filename=$(basename "$file")

    # 校验 Windows 非法特殊字符: : * ? " < > |
    case "$filename" in
      *[\:\*\?\"\<\>\|]*)
        echo "" >&2
        echo "======================================================================" >&2
        echo "❌ [Git Hook 拦截] 文件名包含 Windows 非法字符！" >&2
        echo "======================================================================" >&2
        echo "📌 违规文件: $file" >&2
        echo "📌 规范说明：Windows 文件系统严禁在文件名中使用 : * ? \" < > | 字符。" >&2
        echo "   在 macOS/Linux 提交此类文件会导致 Windows 用户克隆或拉取时发生崩溃。" >&2
        echo "💡 请重命名该文件后重新提交。" >&2
        echo "======================================================================" >&2
        echo "" >&2
        IFS="$OLD_IFS"
        exit 1
        ;;
    esac

    # 校验 Windows 设备保留名: con, prn, aux, nul, com1-com9, lpt1-lpt9
    base_no_ext=$(echo "$filename" | sed -E 's/\.[^.]*$//' | tr '[:upper:]' '[:lower:]')
    case "$base_no_ext" in
      con|prn|aux|nul|com[1-9]|lpt[1-9])
        echo "" >&2
        echo "======================================================================" >&2
        echo "❌ [Git Hook 拦截] 文件名使用了 Windows 系统保留设备名 ($filename)！" >&2
        echo "======================================================================" >&2
        echo "📌 违规文件: $file" >&2
        echo "📌 规范说明：CON, PRN, AUX, NUL, COM1-9, LPT1-9 是 Windows 遗留设备保留字。" >&2
        echo "   提交此类文件会导致 Windows 用户在检出代码时直接报错失败。" >&2
        echo "💡 请重命名该文件后重新提交。" >&2
        echo "======================================================================" >&2
        echo "" >&2
        IFS="$OLD_IFS"
        exit 1
        ;;
    esac
  done
  IFS="$OLD_IFS"
fi

# 4. 路由治理文档校验
staged="$(git diff --cached --name-only --diff-filter=ACMR)"

if ! command -v bun >/dev/null 2>&1; then
  echo "⚠️  [pre-commit] bun 未找到，跳过治理文档校验（CI 会重新执行）。" >&2
  exit 0
fi

if printf '%s\n' "$staged" | grep -qx "AGENTS.md" || printf '%s\n' "$staged" | grep -q "^\.agents/rules/"; then
  bun run verify:agents-md || exit 1
fi

if printf '%s\n' "$staged" | grep -qE "^skills/seal-use/(SKILL\.md|references/[^/]+\.md)$"; then
  bun run verify:skill-md || exit 1
fi

if printf '%s\n' "$staged" | grep -qiE "(^|/)readme"; then
  bun run verify:readme-naming || exit 1
fi

exit 0
