#!/bin/bash
# Pre-commit hook for rust-self-learning-memory
# Ensures code quality before commits

set -e

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

# 0. Validate YAML frontmatter
echo "  ├─ Validating YAML frontmatter..."
if ! bash scripts/check-yaml-frontmatter.sh 2>&1; then
    echo "  ❌ YAML frontmatter validation failed."
    exit 1
fi
echo "  ✅ YAML frontmatter OK"

# 0b. Run yamllint on all YAML files
echo "  ├─ Running yamllint..."
if command -v yamllint &>/dev/null; then
    if ! yamllint . 2>&1; then
        echo "  ❌ yamllint found errors. Please fix before committing."
        exit 1
    fi
    echo "  ✅ yamllint OK"
else
    echo "  ⚠️  yamllint not installed, skipping YAML lint"
fi

# 1. Check code formatting
echo "  ├─ Checking code formatting..."
if ! cargo fmt --all -- --check >/dev/null 2>&1; then
    echo "  ❌ Code is not formatted. Running cargo fmt..."
    cargo fmt --all
    echo "  ✅ Code formatted. Please review changes and commit again."
    exit 1
fi
echo "  ✅ Code formatting OK"

# 2. Run Clippy
echo "  ├─ Running clippy..."
if ! cargo clippy --all -- -D warnings 2>&1 | grep -q "Finished"; then
    echo "  ❌ Clippy warnings found. Please fix before committing."
    cargo clippy --all -- -D warnings
    exit 1
fi
echo "  ✅ Clippy OK"

# 3. Run tests (lib and bins only, skip long-running integration tests)
echo "  ├─ Running tests..."
if ! cargo test --lib --bins --quiet 2>&1 | grep -q "test result: ok"; then
    echo "  ❌ Tests failed. Please fix before committing."
    cargo test --lib --bins
    exit 1
fi
echo "  ✅ Tests OK"

# 4. Run cargo audit (skip if cargo-audit not installed)
echo "  ├─ Running cargo audit..."
if cargo audit --version &>/dev/null 2>&1; then
    if ! cargo audit -q 2>&1; then
        echo "  ❌ Cargo audit found vulnerabilities. Run 'cargo audit' for details."
        cargo audit
        exit 1
    fi
    echo "  ✅ Cargo audit OK"
else
    echo "  ⚠️  cargo-audit not installed, skipping security audit"
fi

# 5. Run documentation tests
echo "  ├─ Running documentation tests..."
if ! ./scripts/check-doctests.sh >/dev/null 2>&1; then
    echo "  ❌ Documentation tests failed. Please fix before committing."
    ./scripts/check-doctests.sh
    exit 1
fi
echo "  ✅ Documentation tests OK"

echo "✅ All pre-commit checks passed!"
