#!/usr/bin/env bash
# pre-push hook: validate Vikunja task exists and tests are fast.
#
# This catches issues that would otherwise only surface in CI:
#   - Branch name missing task ID (e.g., GRM-N)
#   - Vikunja task does not exist for the task ID in the branch name
#   - Unit tests too slow (total > 4s, per-test > 0.5s)
#
# Uses devx.tools.pre_push_check for reusable validation logic.
# Project config (task prefix, Vikunja project ID) is read from
# [tool.devx] in pyproject.toml by devx.config — no hardcoded values here.
#
# Bootstrap resilience: if devx is not importable (e.g., during devx
# upgrades), the hook prints a warning and allows the push.

# Determine the branch being pushed
BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "")

if [ -z "$BRANCH" ] || [ "$BRANCH" = "master" ] || [ "$BRANCH" = "main" ]; then
    exit 0
fi

# Load .env if present (for VIKUNJA_TOKEN)
if [ -f .env ]; then
    set -a
    # shellcheck disable=SC1091
    . .env
    set +a
fi

# Find the Python interpreter with devx installed
if [ -f .venv/bin/python ]; then
    PY=.venv/bin/python
elif [ -x "${HOME}/.pyenv/bin/pyenv" ]; then
    export PYENV_ROOT="${HOME}/.pyenv"
    export PATH="${PYENV_ROOT}/bin:${PYENV_ROOT}/shims:${PATH}"
    eval "$("${PYENV_ROOT}/bin/pyenv" init -)" 2>/dev/null || true
    eval "$("${PYENV_ROOT}/bin/pyenv" virtualenv-init -)" 2>/dev/null || true
    pyenv activate grm 2>/dev/null || true
    PY=python3
else
    PY=python3
fi

# Bootstrap resilience: if devx is not importable, warn but allow the push
if ! $PY -c "import devx.tools.pre_push_check" 2>/dev/null; then
    echo "WARNING: devx not installed — pre-push check skipped."
    echo "Run 'make setup' to install devx."
    exit 0
fi

# Run pre-push validation via devx
$PY -m devx.tools.pre_push_check --branch "$BRANCH" || {
    echo ""
    echo "Pre-push validation failed. Fix the issues above before pushing."
    echo "To bypass (NOT recommended): git push --no-verify"
    exit 1
}

# Check test speed (aligned with CI thresholds)
$PY -m devx.tools.check_test_speed --max-seconds 4 --max-single-seconds 0.5
