#!/bin/sh
set -e

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

# 1. フォーマットチェック
echo "📝 Checking code formatting..."
if ! cargo fmt -- --check; then
    echo ""
    echo "❌ Code is not properly formatted!"
    echo "💡 Run 'cargo fmt' to fix formatting issues"
    exit 1
fi
echo "✅ Format check passed"
echo ""

# 2. Clippy (Linter) - warningsをエラーとして扱う
echo "🔍 Running clippy linter..."
if ! cargo clippy --all-targets --all-features -- -D warnings; then
    echo ""
    echo "❌ Clippy found issues!"
    echo "💡 Fix the warnings above before committing"
    exit 1
fi
echo "✅ Clippy check passed"
echo ""

# 3. ビルドチェック
echo "🔨 Checking if project builds..."
if ! cargo check --all-targets; then
    echo ""
    echo "❌ Build check failed!"
    exit 1
fi
echo "✅ Build check passed"
echo ""

# 4. テスト実行 (nextest)
echo "🧪 Running tests with nextest..."
if command -v cargo-nextest >/dev/null 2>&1; then
    # nextestがインストール済みの場合
    if ! cargo nextest run; then
        echo ""
        echo "❌ Some tests failed!"
        exit 1
    fi
else
    # nextestがない場合は通常のテストを実行
    echo "⚠️  cargo-nextest not found, falling back to standard test runner"
    echo "💡 Install nextest with: cargo install cargo-nextest --locked"
    if ! cargo test; then
        echo ""
        echo "❌ Some tests failed!"
        exit 1
    fi
fi
echo "✅ Tests passed"
echo ""

echo "✨ All pre-commit checks passed successfully!"