#!/bin/bash
# Pre-push hook — runs CI-equivalent checks before every push (branch & tag).
#
# Install:
#   cp scripts/githooks/pre-push .git/hooks/pre-push && chmod +x .git/hooks/pre-push
#
# Skip:
#   MAYSII_SKIP_PRE_PUSH=1 git push ...
#
# Checks (aligned with .github/workflows/ci.yml):
#   1. ruff format --check + ruff check
#   2. mypy src/maysii
#   3. Secret scan (grep patterns matching CI)
#   4. pytest --cov=maysii (full or incremental)

set -e

if [ "${MAYSII_SKIP_PRE_PUSH:-0}" = "1" ]; then
    echo "Pre-push: skipped (MAYSII_SKIP_PRE_PUSH=1)."
    exit 0
fi

PY="${PYTHON:-python3}"
echo "Pre-push: running CI-equivalent checks ($PY)..."
echo ""

# ── 1. Lint (ruff) ───────────────────────────────────────────────
echo "  [1/4] Lint..."
"$PY" -m ruff format --check src tests
"$PY" -m ruff check src tests

# ── 2. Type check (mypy) ────────────────────────────────────────
echo "  [2/4] Type check..."
"$PY" -m mypy src/maysii

# ── 3. Security scan ────────────────────────────────────────────
echo "  [3/4] Security scan..."
SEC_FAIL=0
if grep -rn 'sk-[a-zA-Z0-9]\{20,\}' src/ tests/ --include='*.py' 2>/dev/null; then
    echo "::error::Potential API key found in source code"
    SEC_FAIL=1
fi
if grep -rn 'PRIVATE KEY' src/ tests/ --include='*.py' 2>/dev/null; then
    echo "::error::Private key found in source code"
    SEC_FAIL=1
fi
if grep -rn 'AKIA[0-9A-Z]\{16\}' src/ tests/ --include='*.py' 2>/dev/null \
   | grep -v 'test_' | grep -v '_test\.py'; then
    echo "::error::Potential AWS access key found in source code"
    SEC_FAIL=1
fi
if grep -rn 'gh[pous]_[a-zA-Z0-9]\{36,\}' src/ tests/ --include='*.py' 2>/dev/null \
   | grep -v 'test_' | grep -v '_test\.py'; then
    echo "::error::Potential GitHub token found in source code"
    SEC_FAIL=1
fi
[ "$SEC_FAIL" -eq 1 ] && exit 1

# ── 4. Tests ────────────────────────────────────────────────────
echo "  [4/4] Tests..."
if [ "${MAYSII_PRE_PUSH_TEST_MODE:-full}" = "incremental" ]; then
    "$PY" scripts/pytest_scope.py run --mode incremental --base "${MAYSII_TEST_BASE:-origin/master}" -- \
        --cov=maysii --cov-report=term-missing -x --tb=line tests/
else
    "$PY" -m pytest --cov=maysii --cov-report=term-missing tests/ -x --tb=line
fi

echo ""
echo "Pre-push: all checks passed."
