#!/bin/bash
# Pre-push hook: run buffer-protocol smoke tests under valgrind on master pushes.
# Install: ln -sf ../../.githooks/pre-push .git/hooks/pre-push

set -euo pipefail

ZERO_COMMIT="0000000000000000000000000000000000000000"
while read LOCAL_REF LOCAL_SHA REMOTE_REF REMOTE_SHA; do
    if [ "$REMOTE_REF" = "refs/heads/master" ]; then
        MASTER_PUSH=1
    fi
done

if [ -z "${MASTER_PUSH:-}" ]; then
    exit 0
fi

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

VENV_PYTHON="$REPO_ROOT/venv/py312/x86_64/bin/python3"
if [ -x "$VENV_PYTHON" ]; then
    PYTHON="$VENV_PYTHON"
else
    PYTHON="python3"
fi

if command -v valgrind &>/dev/null; then
    echo "Running smoke tests under valgrind..."
    valgrind \
        --tool=memcheck \
        --leak-check=full \
        --error-exitcode=1 \
        --errors-for-leak-kinds=definite \
        --track-origins=yes \
        $PYTHON -m pytest "$REPO_ROOT/tests/test_buffer.py" -v 2>&1 || {
        echo "FAILED: Memory safety check detected errors!"
        echo "Run locally: valgrind --leak-check=full --track-origins=yes"
        echo "  python3 -m pytest tests/test_buffer.py -v"
        exit 1
    }
    echo "Memory check passed."
else
    echo "valgrind not installed, falling back to plain smoke tests..."
    $PYTHON -m pytest "$REPO_ROOT/tests/test_buffer.py" -v 2>&1 || {
        echo "FAILED: Smoke tests failed!"
        exit 1
    }
    echo "Smoke tests passed."
fi
