#!/bin/sh

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

echo "Running pre-push checks..."

# Function to check if a command exists
command_exists() {
    command -v "$1" >/dev/null 2>&1
}

# Check if uv is installed
if ! command_exists uv; then
    echo -e "${RED}Error: uv is not installed. Please install it first:${NC}"
    echo "curl -LsSf https://astral.sh/uv/install.sh | sh"
    exit 1
fi

# Check if gitleaks is installed
if ! command_exists gitleaks; then
    echo -e "${RED}Error: gitleaks is not installed. Please install it first:${NC}"
    echo "brew install gitleaks # or see https://github.com/gitleaks/gitleaks#installation"
    exit 1
fi

# Install dependencies if needed
echo "Installing dependencies..."
uv pip install --system -e ".[dev]"

# Run gitleaks secret scan
if ! gitleaks detect -v --log-opts="" --config gitleaks.toml; then
    echo -e "${RED}Gitleaks detected potential secrets! Please review and remove them before pushing.${NC}"
    exit 1
fi

# Run pytest with coverage
echo "Running tests..."
if ! pytest tests/ -v --cov=trustwise --cov-report=term-missing; then
    echo -e "${RED}Tests failed!${NC}"
    exit 1
fi

# Run ruff linting
echo "Running linting checks..."
if ! ruff check src tests; then
    echo -e "${RED}Linting failed!${NC}"
    exit 1
fi

# Build documentation
echo "Building documentation..."
if ! sphinx-build -b html docs/source docs/_build/html; then
    echo -e "${RED}Documentation build failed!${NC}"
    exit 1
fi

echo -e "${GREEN}All checks passed!${NC}"
exit 0 