#!/usr/bin/env sh

set -eu

REPO_ROOT="$(git rev-parse --show-toplevel)"
PYTHON_BIN="python3"
if [ -x "$REPO_ROOT/.venv/bin/python" ]; then
  PYTHON_BIN="$REPO_ROOT/.venv/bin/python"
elif ! command -v "$PYTHON_BIN" >/dev/null 2>&1; then
  PYTHON_BIN="python"
fi

echo "Running test suite before push..."

if ! (cd "$REPO_ROOT" && "$PYTHON_BIN" -m pytest); then
  echo ""
  echo "Push blocked: tests failed."
  exit 1
fi

echo "Running dependency security audit before push..."

if ! "$PYTHON_BIN" -m pip_audit --version >/dev/null 2>&1; then
  echo ""
  echo "Push blocked: pip-audit is not installed for $PYTHON_BIN."
  echo "Install it with: $PYTHON_BIN -m pip install pip-audit"
  exit 1
fi

# Scan project dependencies (from the local project) and fail when known vulnerabilities exist.
if ! "$PYTHON_BIN" -m pip_audit --progress-spinner off .; then
  echo ""
  echo "Push blocked: dependency security issues are pending."
  echo "Fix or explicitly resolve the reported vulnerabilities, then push again."
  exit 1
fi

echo "Tests and security audit passed. Continuing push."
