#!/usr/bin/env bash
# pre-push hook — runs the EXACT same lint + test commands as GitLab CI.
# Catches failures BEFORE CI, not after.
#
# To bypass in an emergency: git push --no-verify
# To install: cp scripts/hooks/pre-push .git/hooks/pre-push && chmod +x .git/hooks/pre-push
#
# CI equivalence:
#   Lint:  .gitlab-ci.yml → lint job → ruff check src/ --select E,F,W --ignore E501
#   Tests: .gitlab-ci.yml → test:unit job → pytest -m "not integration"

set -euo pipefail

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

# Activate venv if not already active
if [ -z "${VIRTUAL_ENV:-}" ]; then
  if [ -f "$REPO_ROOT/../.venv/bin/activate" ]; then
    # shellcheck disable=SC1091
    source "$REPO_ROOT/../.venv/bin/activate"
  elif [ -f "$REPO_ROOT/.venv/bin/activate" ]; then
    source "$REPO_ROOT/.venv/bin/activate"
  fi
fi

# ── Ruff lint (EXACT match with CI lint job) ────────────────────────────
echo "▶ pre-push: running ruff linter..."

if ruff check src/ --select E,F,W --ignore E501; then
  echo "✓ pre-push: ruff passed"
else
  echo ""
  echo "✗ pre-push: ruff found errors — push blocked"
  echo "  Run: ruff check src/ --select E,F,W --ignore E501 --fix"
  exit 1
fi

# ── Test suite (matches CI test:unit job) ───────────────────────────────
echo "▶ pre-push: running test suite (unit only, no integration)..."

if python -m pytest tests/ src/neutron_os/extensions/builtins/ \
    -m "not integration" \
    --tb=short -q \
    --no-header \
    2>&1; then
  echo "✓ pre-push: all tests passed"
else
  echo ""
  echo "✗ pre-push: tests failed — push blocked"
  echo "  Fix the failures above, or use --no-verify to bypass"
  exit 1
fi
