#!/bin/bash
set -e

echo "🚀 Running pre-push checks..."

# Final security check before push
echo "🔒 Final security scan..."
if command -v gitleaks &> /dev/null; then
    echo "  • Running comprehensive secret scan..."
    gitleaks detect --source . --verbose || {
        echo "❌ Security scan failed! Cannot push with potential secrets."
        exit 1
    }
else
    echo "  • gitleaks not found, install with: brew install gitleaks"
fi

# Check for dependency vulnerabilities
echo "🛡️  Checking dependencies for vulnerabilities..."
npm audit --audit-level moderate || {
    echo "⚠️  High/critical vulnerabilities found. Consider running 'npm audit fix'"
    echo "📝 You can still push, but please address vulnerabilities soon."
}

# Run node compatibility check if Makefile exists
if [ -f "Makefile" ]; then
    echo "📦 Checking Node.js compatibility..."
    make node-compat || echo "⚠️  Node compatibility check failed, but continuing"
fi

# Build check
echo "🔨 Final build check..."
npm run build || {
    echo "❌ Build failed! Cannot push broken build."
    exit 1
}

# Run test suite (allow some failures for performance tests)
echo "🧪 Running test suite..."
if npm run test; then
    echo "✅ All tests passed!"
else
    echo "⚠️  Some tests failed, but continuing (performance tests have known issues)"
    echo "📝 Please investigate test failures when possible"
fi

echo "✅ Pre-push checks completed!"