#!/usr/bin/env bash
# Pre-push hook: run the FAST local checks before push.
#
# Runs the `ci-fast` task from pyproject.toml — lint, format-check, typecheck and
# the private-link guard. Seconds, not minutes.
#
# It deliberately does NOT run the test suite. Two reasons:
#
#   1. GitHub Actions runs the full matrix on every PR, so a multi-minute local
#      re-run buys little and is paid on every single push.
#   2. Correctness, not just speed: git opens the connection to the remote ~1s BEFORE
#      running this hook, and GitHub closes an idle git-receive-pack session after
#      ~5 minutes. A hook that outlasts that makes git write the pack to a dead
#      socket and die with exit 141 (SIGPIPE) — hook passes, nothing transferred,
#      no error printed. Full `task ci` measured 395s and failed 3/3; `ci-fast`
#      measures ~4.5s. See
#      docs/solutions/integration-issues/long-pre-push-hook-makes-git-push-to-github-fail-with-sigpipe.md
#
# Run `task ci` yourself before opening a PR.
#
# This is the versioned source of truth — the actual hook lives at
# .git/hooks/pre-push (per-clone), installed by scripts/install-git-hooks.sh.
#
# Bypass with `git push --no-verify` for emergencies (e.g. work-in-progress
# branch pushes for backup or sharing). Don't bypass before a PR merges.

set -euo pipefail

say()  { printf '\n\033[1;36m== %s ==\033[0m\n' "$*"; }
ok()   { printf '  \033[1;32mOK\033[0m %s\n' "$*"; }
fail() { printf '  \033[1;31mFAIL\033[0m %s\n' "$*"; exit 1; }

# Make sure we're using the project's Python environment so `task` resolves.
# The venv is a sibling of this script's repo root, so find it rather than
# requiring the caller to have activated it — an unactivated venv used to abort
# the push with a bare "task not found".
if ! command -v task >/dev/null 2>&1; then
  repo_root="$(git rev-parse --show-toplevel 2>/dev/null || true)"
  if [ -n "$repo_root" ] && [ -x "$repo_root/.venv/bin/task" ]; then
    PATH="$repo_root/.venv/bin:$PATH"
    export PATH
  fi
fi

if ! command -v task >/dev/null 2>&1; then
  fail "task not found on PATH — activate the project venv (source .venv/bin/activate) and re-run, or install dev deps with: pip install -e .[dev]"
fi

say "Running fast local checks (task ci-fast)"
echo "  lint + format-check + typecheck + private-link guard."
echo "  Full suite runs in CI; run \`task ci\` yourself before opening a PR."
echo "  Bypass with \`git push --no-verify\` if you need to push WIP."
echo

if task ci-fast; then
  ok "pre-push: fast checks passed locally"
else
  fail "pre-push: local checks failed — fix before pushing (or --no-verify for WIP)"
fi
