#!/bin/bash
# Pre-push hook: Comprehensive quality checks (linting + formatting + docstrings + tests)
# Skip with: git push --no-verify

set -e

# Unset GIT_DIR/GIT_WORK_TREE so that uv's internal git fetch calls
# (for git-based dependencies) don't inherit the hook's git context.
unset GIT_DIR GIT_WORK_TREE

echo "Running pre-push checks..."

# Sync dev dependencies first
echo "→ Syncing dev dependencies..."
if ! uv sync --all-extras; then
    echo "✗ Dev dependency sync failed. Please check your environment."
    exit 1
fi

# Verify no committed notebook still embeds video outputs
TRACKED_NOTEBOOKS=$(git ls-files '*.ipynb')
if [ -n "$TRACKED_NOTEBOOKS" ]; then
    echo "→ Checking notebooks for embedded video outputs..."
    if ! echo "$TRACKED_NOTEBOOKS" | xargs -d '\n' uv run python scripts/strip_notebook_videos.py --check; then
        echo "✗ Notebook(s) above embed video outputs. Strip and re-commit:"
        echo "    python scripts/strip_notebook_videos.py <paths>"
        exit 1
    fi
fi

# Run Ruff formatting first
echo "→ Running Ruff formatting..."
if ! uv run ruff format .; then
    echo "✗ Ruff formatting failed. Please fix the errors and try again."
    exit 1
fi

# Run Ruff linting with auto-fix (on formatted code)
echo "→ Running Ruff linting (with auto-fix)..."
if ! uv run ruff check . --fix; then
    echo "✗ Ruff linting failed. Please fix the errors and try again."
    exit 1
fi

# Check docstring coverage
echo "→ Checking docstring coverage (≥95%)..."
if ! uv run python -m interrogate -v cuvis_ai/ --fail-under 95; then
    echo ""
    echo "✗ Docstring coverage check failed!"
    echo "  Coverage is below 95% threshold."
    echo ""
    echo "  To see detailed missing docstrings:"
    echo "    interrogate -vv cuvis_ai/"
    echo ""
    echo "  See docstring guide: docs/development/docstrings.md"
    echo ""
    echo "  To skip this check (not recommended):"
    echo "    git push --no-verify"
    echo ""
    exit 1
fi

# Run pytest with non-GPU tests
echo "→ Running pytest (excluding GPU tests)..."
if ! uv run python -m pytest tests/ -v --tb=line -m "not slow and not gpu"; then
    echo "✗ Tests failed. Please fix the failing tests and try again."
    exit 1
fi

echo "✓ All pre-push checks passed!"
exit 0
