#!/bin/bash
#
# pre-commit Hook for Limiteron Project
#
# This hook runs before git commit to ensure code quality.
# It performs the following checks:
# 1. Code formatting (cargo fmt)
# 2. Linting (cargo clippy)
# 3. Compilation check (cargo check)
# 4. Unit tests (cargo test --lib)
#
# Usage:
#   Install: cp scripts/pre-commit .git/hooks/pre-commit
#   Or: scripts/install-pre-commit.sh
#

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

# Print functions
print_header() {
    echo -e "${BLUE}════════════════════════════════════════════════════════════${NC}"
    echo -e "${BLUE}  $1${NC}"
    echo -e "${BLUE}════════════════════════════════════════════════════════════${NC}"
}

print_success() {
    echo -e "${GREEN}✓ $1${NC}"
}

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

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

print_info() {
    echo -e "${BLUE}ℹ $1${NC}"
}

# Track overall status
OVERALL_STATUS=0
FAILED_CHECKS=()

# Timer
START_TIME=$(date +%s)

# Get project root directory
PROJECT_ROOT=$(git rev-parse --show-toplevel 2>/dev/null || echo ".")
cd "$PROJECT_ROOT"

print_header "Limiteron Pre-commit Hook"

print_info "Project: $(basename "$PROJECT_ROOT")"
print_info "Rust version: $(rustc --version 2>/dev/null || echo 'not installed')"
echo ""

# Function to run a check
run_check() {
    local check_name=$1
    local check_command=$2
    local error_message=$3

    print_info "Running: $check_name..."

    if eval "$check_command" > /dev/null 2>&1; then
        print_success "$check_name passed"
        return 0
    else
        print_error "$check_name failed"
        echo -e "    ${YELLOW}Error: $error_message${NC}"
        OVERALL_STATUS=1
        FAILED_CHECKS+=("$check_name")
        return 1
    fi
}

# Function to run a check with output
run_check_with_output() {
    local check_name=$1
    local check_command=$2
    local error_message=$3

    print_info "Running: $check_name..."

    if eval "$check_command" 2>&1; then
        print_success "$check_name passed"
        return 0
    else
        print_error "$check_name failed"
        echo -e "    ${YELLOW}Error: $error_message${NC}"
        OVERALL_STATUS=1
        FAILED_CHECKS+=("$check_name")
        return 1
    fi
}

# Check if rust is installed
if ! command -v rustc &> /dev/null; then
    print_warning "Rust not found. Skipping Rust-specific checks."
    print_info "Install Rust from: https://rustup.rs/"
    exit 0
fi

# Check if we're in a rust project
if [ ! -f "Cargo.toml" ]; then
    print_warning "No Cargo.toml found. Skipping Rust checks."
    exit 0
fi

echo "Running pre-commit checks..."
echo ""

# 1. Code Formatting Check
print_header "1. Code Formatting"
run_check_with_output "Format Check" \
    "cargo fmt --all -- --check" \
    "Code formatting issues found. Run 'cargo fmt' to fix."

echo ""

# 2. Clippy Linting
print_header "2. Clippy Linting"
run_check "Clippy Check" \
    "cargo clippy --all-features -- -A clippy::unnested-or-lower -D warnings" \
    "Clippy found issues. Review the output above."

echo ""

# 3. Compilation Check
print_header "3. Compilation Check"
run_check "Build Check" \
    "cargo check --all-features" \
    "Compilation failed. Check the errors above."

echo ""

# 4. Unit Tests (fast subset)
print_header "4. Unit Tests"
run_check "Unit Tests" \
    "cargo test --lib --all-features -- --test-threads=4" \
    "Unit tests failed. Check the test output above."

echo ""

# Calculate elapsed time
END_TIME=$(date +%s)
ELAPSED=$((END_TIME - START_TIME))

# Summary
print_header "Summary"

if [ $OVERALL_STATUS -eq 0 ]; then
    print_success "All pre-commit checks passed!"
    echo ""
    echo -e "${GREEN}Elapsed time: ${ELAPSED}s${NC}"
    echo ""
    exit 0
else
    print_error "Some checks failed!"
    echo ""
    echo -e "${RED}Failed checks:${NC}"
    for check in "${FAILED_CHECKS[@]}"; do
        echo -e "  - $check"
    done
    echo ""
    echo -e "${YELLOW}Please fix the issues above before committing.${NC}"
    echo ""
    echo -e "${BLUE}Quick fix commands:${NC}"
    echo -e "  ${BLUE}Formatting:${NC}    cargo fmt"
    echo -e "  ${BLUE}Clippy:${NC}       cargo clippy --all-features -- -D warnings"
    echo -e "  ${BLUE}Build:${NC}        cargo check --all-features"
    echo -e "  ${BLUE}Tests:${NC}        cargo test --lib --all-features"
    echo ""
    echo -e "${RED}Elapsed time: ${ELAPSED}s${NC}"
    exit 1
fi
