#!/usr/bin/env bash
# AuroraView pre-commit hook
# Ensures Python & Rust lint pass before committing.
# Requires: ruff and cargo available on PATH for their respective checks.

set -euo pipefail

# Resolve ruff command (prefer direct, fallback to uvx)
if command -v ruff >/dev/null 2>&1; then
  RUFF_CMD="ruff"
elif command -v uvx >/dev/null 2>&1; then
  RUFF_CMD="uvx ruff"
elif command -v uv >/dev/null 2>&1; then
  RUFF_CMD="uvx ruff"
else
  RUFF_CMD=""
fi

# Detect changed files in index (staged)
changed_files=$(git diff --cached --name-only --diff-filter=ACM || true)

# ---------- Python (ruff) ----------
if echo "$changed_files" | grep -E '^(python/|tests/).*\.py$' >/dev/null 2>&1; then
  py_changed=$(echo "$changed_files" | grep -E '^(python/|tests/).*\.py$' || true)

  if [ -z "$RUFF_CMD" ]; then
    echo "[pre-commit] ruff not found (and uv/uvx not available); skipping Python checks"
  else
    echo "[pre-commit] Running ruff format on staged Python files"
    $RUFF_CMD format $py_changed

    echo "[pre-commit] Running ruff check --fix on staged Python files"
    $RUFF_CMD check --fix $py_changed

    echo "[pre-commit] Running ruff check (repo-level)"
    $RUFF_CMD check python/ tests/
  fi
else
  echo "[pre-commit] Skipping ruff (no Python changes staged)"
fi

# ---------- Rust (fmt + clippy) ----------
if echo "$changed_files" | grep -E '(^src/.*\.rs$|^Cargo\.toml$|^build\.rs$)' >/dev/null 2>&1; then
  if command -v cargo >/dev/null 2>&1; then
    echo "[pre-commit] Running cargo fmt --all -- --check"
    cargo fmt --all -- --check

    echo "[pre-commit] Running cargo clippy --all-targets --all-features -- -D warnings"
    cargo clippy --all-targets --all-features -- -D warnings
  else
    echo "[pre-commit] cargo not found; skipping Rust checks"
  fi
else
  echo "[pre-commit] Skipping cargo (no Rust changes staged)"
fi

echo "[pre-commit] OK"
