#!/usr/bin/env bash
# ============================================================
# Finlet — pre-push hook
# ============================================================
#
# Runs the local CI gate before a push is allowed to leave the
# laptop. Mirrors the GitHub Actions pipeline order so anything
# that would break CI breaks here first:
#
#   1. ruff check finlet/ tests/        (~3s)
#   2. mypy finlet/ --ignore-missing-imports  (~15s)
#   3. pytest tests/ -q --tb=short      (~5min)
#   4. e2e smoke (6 journeys)           (~90-120s)
#
# Step 4 was added 2026-05-03 — see
# `docs/decisions/e2e-in-pre-push-gate.md`. Closes the gap where
# bug-hunt's "fix shipped" report could lie because the e2e gate
# in CI fails AFTER the local gate passes.
#
# This file is checked into `scripts/git-hooks/` so it stays in
# version control. To activate it locally, run:
#
#     bash scripts/setup-git-hooks.sh
#
# The setup script symlinks this file into `.git/hooks/pre-push`.
# Per-step skip env vars:
#   SKIP_E2E_SMOKE=1 git push   # bypass step 4 only
# ============================================================

set -uo pipefail

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

# Activate the virtualenv
if [ ! -f .venv/bin/activate ]; then
    echo "ERROR: .venv not found at $REPO_ROOT/.venv"
    echo "Create it with: python3 -m venv .venv && pip install -e '.[dev]'"
    exit 1
fi
# shellcheck source=/dev/null
source .venv/bin/activate

echo "=== Pre-push checks ==="
echo ""

# 1. Lint
echo "[1/4] ruff check finlet/ tests/"
if ! ruff check finlet/ tests/; then
    echo ""
    echo "FAILED: ruff found lint errors. Fix them before pushing."
    exit 1
fi
echo "PASSED"
echo ""

# 2. Type check
echo "[2/4] mypy finlet/ --ignore-missing-imports"
if ! mypy finlet/ --ignore-missing-imports; then
    echo ""
    echo "FAILED: mypy found type errors. Fix them before pushing."
    exit 1
fi
echo "PASSED"
echo ""

# 3. Tests
echo "[3/4] pytest tests/ -q --tb=short"
if ! pytest tests/ -q --tb=short; then
    echo ""
    echo "FAILED: tests did not pass. Fix them before pushing."
    exit 1
fi
echo "PASSED"
echo ""

# 4. E2E smoke (6 journeys: login, trade, settings ×2, leaderboard, benchmark-blindness)
echo "[4/4] scripts/e2e-smoke.sh"
SMOKE_SCRIPT="$REPO_ROOT/scripts/e2e-smoke.sh"
if [[ ! -x "$SMOKE_SCRIPT" ]]; then
    echo "WARN: $SMOKE_SCRIPT not executable — skipping (run chmod +x to enable)" >&2
elif ! bash "$SMOKE_SCRIPT"; then
    echo ""
    echo "FAILED: e2e smoke failed. Fix the regression or set SKIP_E2E_SMOKE=1 to bypass."
    exit 1
fi
echo ""

echo "=== All pre-push checks passed ==="
