#!/usr/bin/env bash
set -euo pipefail

REPO_ROOT=$(git rev-parse --show-toplevel 2>/dev/null || echo ".")

echo "Running pre-commit checks..."

# Check if Cargo is available
if ! command -v cargo &> /dev/null; then
    echo "⚠️  cargo not found, skipping Rust checks" >&2
    exit 0
fi

# 1. Run cargo fmt check
echo "🎨 Checking code formatting..."
if ! cargo fmt -- --check; then
    echo "" >&2
    echo "❌ Code formatting check failed" >&2
    echo "Run 'cargo fmt' to fix formatting issues" >&2
    echo "Or use 'git commit --no-verify' to bypass (not recommended)" >&2
    exit 1
fi

# 2. Run cargo clippy
echo "🔍 Running clippy lints..."
if ! cargo clippy --all-targets --all-features -- -D warnings; then
    echo "" >&2
    echo "❌ Clippy found issues" >&2
    echo "Fix the warnings above or use 'git commit --no-verify' to bypass" >&2
    exit 1
fi

# 3. Run secret scanning
echo "🔒 Scanning for secrets..."
if command -v python3 &> /dev/null; then
    if ! python3 "$REPO_ROOT/scripts/check_secrets.py"; then
        exit 1
    fi
else
    echo "⚠️  python3 not found, skipping secret scan" >&2
fi

echo "✅ All pre-commit checks passed"
exit 0
