#!/usr/bin/env bash

# Pre-push hook for kiteticker-async-manager
# This runs comprehensive checks before pushing to prevent CI failures

set -e

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

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Function to print colored output
print_status() {
    echo -e "${GREEN}✓${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}⚠${NC} $1"
}

print_error() {
    echo -e "${RED}✗${NC} $1"
}

# Check if we're in the right directory
if [ ! -f "Cargo.toml" ]; then
    print_error "Not in a Rust project directory!"
    exit 1
fi

echo "📋 Running formatting checks..."
if ! cargo fmt --check; then
    print_error "Code formatting issues found!"
    echo "Run: cargo fmt"
    exit 1
fi
print_status "Code formatting is correct"

echo "🔍 Running linting..."
if ! cargo clippy --all-features -- -D warnings; then
    print_error "Clippy linting failed!"
    echo "Fix clippy warnings before pushing"
    exit 1
fi
print_status "Linting passed"

echo "🏗️  Building project..."
if ! cargo build --all-features; then
    print_error "Build failed!"
    exit 1
fi
print_status "Build successful"

echo "🧪 Running comprehensive tests..."
if ! cargo test --all-features; then
    print_error "Tests failed!"
    exit 1
fi
print_status "All tests passed"

echo "📚 Running doc tests..."
if ! cargo test --doc --all-features; then
    print_error "Doc tests failed!"
    exit 1
fi
print_status "Doc tests passed"

echo "📖 Checking documentation (lib, all features, private items)..."
# Build comprehensive docs for the library target only to avoid known Cargo resolver panics
if ! cargo doc --no-deps --lib --all-features --document-private-items; then
    print_error "Documentation build failed!"
    exit 1
fi
print_status "Documentation builds successfully"

echo "🔒 Running security audit..."
if command -v cargo-audit > /dev/null; then
    if ! cargo audit; then
        print_error "Security audit failed!"
        exit 1
    fi
    print_status "Security audit passed"
else
    print_warning "cargo-audit not installed, skipping security audit"
    echo "Install with: cargo install cargo-audit"
fi

echo "📦 Testing publish readiness..."
if ! cargo publish --dry-run --all-features; then
    print_error "Publish dry run failed!"
    exit 1
fi
print_status "Package is ready for publishing"

echo ""
echo -e "${GREEN}🎉 All pre-push checks passed!${NC}"
echo "Your code is ready to be pushed to the repository."
