#!/bin/sh
# pre-commit — frontmatter validation + large file guard + secret scan

# 1. Frontmatter validation for wiki pages
CHANGED=$(git diff --cached --name-only --diff-filter=ACM | grep '^wiki/.*\.md$')
if [ -n "$CHANGED" ]; then
    python tools/scripts/validate-frontmatter.py --git-hook
    if [ $? -ne 0 ]; then
        echo "ERROR: Frontmatter validation failed. Commit rejected."
        echo "Run 'python tools/scripts/validate-frontmatter.py --files <file>' to check."
        exit 1
    fi
fi

# 2. Large file guard (>10MB) — prevent accidental PDF/video/attachment commits
MAX_SIZE=10485760  # 10 MB
REJECT=""
for f in $(git diff --cached --name-only --diff-filter=ACM); do
    [ -f "$f" ] || continue
    FSIZE=$(wc -c < "$f" 2>/dev/null | tr -d ' ')
    [ -z "$FSIZE" ] && FSIZE=0
    if [ "$FSIZE" -gt "$MAX_SIZE" ]; then
        REJECT="$REJECT
  $f ($FSIZE bytes)"
    fi
done
if [ -n "$REJECT" ]; then
    echo "ERROR: Files exceed 10MB limit (rejected):$REJECT"
    echo "Use Git LFS or add to .gitignore."
    exit 1
fi

# 3. Secret scan — long hex tokens (40+ chars) in staged diff (warning only)
LEAK=$(git diff --cached -U0 2>/dev/null | grep -iE '[0-9a-f]{40,}' | grep -v 'sha' | head -5)
if [ -n "$LEAK" ]; then
    echo "WARN: Possible token/secret in staged diff (review before push):"
    echo "$LEAK"
fi

exit 0
