#!/bin/sh
# Pre-push hook: mypy + full pytest before code leaves the local machine.
# Per-commit stays fast (isort/black/ruff only). This is where slow checks live.

if [ -x ".venv/bin/python3" ]; then
    PY=".venv/bin/python3"
else
    PY="python3"
fi

echo "pre-push: checking mypy..."
mypy_out=$("$PY" -m mypy src/servicenow_mcp/ --ignore-missing-imports --no-error-summary 2>&1)
mypy_status=$?
echo "$mypy_out" | grep -v "annotation-unchecked"
if [ "$mypy_status" -ne 0 ]; then
    echo ""
    echo "BLOCKED: mypy type errors. Re-run for details:"
    echo "  $PY -m mypy src/servicenow_mcp/ --ignore-missing-imports"
    exit 1
fi

echo "pre-push: running full pytest..."
pytest_out=$("$PY" -m pytest tests/ -q --no-header 2>&1)
pytest_status=$?
echo "$pytest_out" | tail -5
if [ "$pytest_status" -ne 0 ]; then
    echo ""
    echo "BLOCKED: pytest failed. Investigate failures before pushing."
    echo "  $PY -m pytest tests/"
    exit 1
fi

# Version-tag consistency: pushing a tag vX.Y.Z whose version does not match
# pyproject.toml would pass CI tests but fail the PyPI publish step remotely
# (happened on v1.18.35/36: a broken && chain skipped the version bump and a
# silent no-op replace masked it). Catch it BEFORE the tag leaves the machine.
pkg_version=$(grep -m1 '^version = ' pyproject.toml | sed 's/version = "\(.*\)"/\1/')
while read -r _local_ref _local_sha remote_ref _remote_sha; do
    case "$remote_ref" in
        refs/tags/v*)
            tag_version="${remote_ref#refs/tags/v}"
            if [ "$tag_version" != "$pkg_version" ]; then
                echo ""
                echo "BLOCKED: tag v$tag_version does not match pyproject.toml version $pkg_version."
                echo "  Bump pyproject.toml (and commit it) before tagging, or fix the tag."
                exit 1
            fi
            ;;
    esac
done
