#!/bin/bash
#
# Pre-push hook: Validate documentation before push (optional)
#
# This hook runs before a push is executed. It can validate documentation
# quality, check for broken links, or enforce documentation standards.
#
# Installation: Copy to .git/hooks/pre-push or use install-hooks.sh
# Note: This is an optional validation hook

set -e

# Configuration
DOC_PATTERNS='\.md$|\.rst$|\.txt$|docs/.*\.py$'
ENABLE_VALIDATION=${GIT_HOOK_VALIDATE_DOCS:-false}

# Skip validation if not explicitly enabled
if [ "$ENABLE_VALIDATION" != "true" ]; then
    exit 0
fi

echo "🔍 Validating documentation before push..."

# Read stdin to get push details
while read local_ref local_sha remote_ref remote_sha; do
    if [ "$local_sha" = "0000000000000000000000000000000000000000" ]; then
        # Deleting a branch, skip validation
        continue
    fi

    if [ "$remote_sha" = "0000000000000000000000000000000000000000" ]; then
        # New branch, check all commits
        range="$local_sha"
    else
        # Existing branch, check commits since remote
        range="$remote_sha..$local_sha"
    fi

    # Get changed documentation files in this push
    CHANGED_DOCS=$(git diff --name-only --diff-filter=AM "$range" | grep -E "$DOC_PATTERNS" || true)

    if [ -z "$CHANGED_DOCS" ]; then
        continue
    fi

    # Count changed files
    DOC_COUNT=$(echo "$CHANGED_DOCS" | wc -l | tr -d ' ')
    echo "  📝 Found $DOC_COUNT documentation file(s) to validate"

    # Basic validation: Check if files are not empty
    VALIDATION_FAILED=false
    while IFS= read -r doc_file; do
        if [ -z "$doc_file" ]; then
            continue
        fi

        # Check if file exists and is not empty
        if [ ! -f "$doc_file" ]; then
            echo "  ❌ File not found: $doc_file"
            VALIDATION_FAILED=true
        elif [ ! -s "$doc_file" ]; then
            echo "  ⚠️  Warning: Empty file: $doc_file"
        else
            echo "  ✓ Valid: $doc_file"
        fi
    done <<< "$CHANGED_DOCS"

    # Fail push if validation failed
    if [ "$VALIDATION_FAILED" = "true" ]; then
        echo ""
        echo "❌ Documentation validation failed. Push rejected."
        echo "   Fix the issues above or disable validation with:"
        echo "   export GIT_HOOK_VALIDATE_DOCS=false"
        exit 1
    fi
done

echo "✓ Documentation validation passed"
exit 0
