#!/usr/bin/env bash

set -euo pipefail

repo_root="$(git rev-parse --show-toplevel)"
cd "$repo_root"

python_cmd=""

if [[ -x "$repo_root/.venv/bin/python" ]]; then
    python_cmd="$repo_root/.venv/bin/python"
elif command -v python3 >/dev/null 2>&1; then
    python_cmd="$(command -v python3)"
fi

if [[ -z "$python_cmd" ]] || ! "$python_cmd" -m ruff --version >/dev/null 2>&1; then
    echo "ruff is required for this hook. Install Python dev dependencies first." >&2
    exit 1
fi

mapfile -d '' staged_python_files < <(
    git diff --cached --name-only --diff-filter=ACMR -z -- '*.py'
)

if ((${#staged_python_files[@]} > 0)); then
    echo "Running ruff check --fix on staged Python files..."
    "$python_cmd" -m ruff check --fix "${staged_python_files[@]}"
    echo "Running ruff format on staged Python files..."
    "$python_cmd" -m ruff format "${staged_python_files[@]}"
    echo "Adding modified files back to staging area..."
    git add -- "${staged_python_files[@]}"
else
    echo "No staged Python files to lint with ruff."
fi

if ((${#staged_python_files[@]} > 0)); then
    echo "Running pyright on staged Python files..."
    "$python_cmd" -m pyright "${staged_python_files[@]}"
else
    echo "No staged Python files to type check with pyright."
fi
