#!/usr/bin/env bash
# Pre-commit hook: check formatting and linting before commit.
# Install: cp hooks/pre-commit .git/hooks/pre-commit && chmod +x .git/hooks/pre-commit
# Or:      git config core.hooksPath hooks

set -e

# Rust formatting
if git diff --cached --name-only | grep -qE '\.rs$'; then
    printf "  %-12s" "rust fmt"
    cargo fmt --check 2>&1 | head -20
    if [ ${PIPESTATUS[0]} -ne 0 ]; then
        echo "pre-commit: formatting check failed. Run 'cargo fmt' and try again."
        exit 1
    fi
    echo "ok"
fi

# Python linting
if git diff --cached --name-only | grep -qE 'python/|\.py$'; then
    if command -v ruff >/dev/null 2>&1; then
        printf "  %-12s" "ruff"
        ruff check python/ && echo "ok" || {
            echo "pre-commit: ruff check failed. Run 'ruff check --fix python/' and try again."
            exit 1
        }
    fi
fi

# Node linting
if git diff --cached --name-only | grep -qE 'node/'; then
    if [ -f node/node_modules/.bin/biome ]; then
        printf "  %-12s" "biome"
        (cd node && npx biome check) && echo "ok" || {
            echo "pre-commit: biome check failed. Run 'cd node && npm run format' and try again."
            exit 1
        }
    fi
fi
