#!/bin/sh
# Pre-push hook: run all tests before allowing push
# Install: cp scripts/pre-push .git/hooks/pre-push

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

# README devices table must match devices/*/descriptor.json. If it has
# drifted, regenerate it on disk so the developer just has to `git add`
# and retry; do not push with stale docs.
echo "📋 Checking README devices table..."
if ! python3 "${REPO_ROOT}/scripts/generate-readme-devices.py" --check > /dev/null 2>&1; then
    echo "⚠️  README.md device table is out of sync with devices/*/descriptor.json."
    python3 "${REPO_ROOT}/scripts/generate-readme-devices.py" > /dev/null
    echo "   Regenerated README.md. Review the diff, then:"
    echo "     git add README.md && git commit --amend --no-edit   # fold into the last commit"
    echo "   or make a fresh commit and re-push."
    exit 1
fi

echo "🔍 Running tests before push..."

# Set XDG_DATA_DIRS so DeviceRegistry finds JSON descriptors in the build tree
REPO_ROOT="$(git rev-parse --show-toplevel)"
export XDG_DATA_DIRS="${REPO_ROOT}/build:${XDG_DATA_DIRS:-/usr/local/share:/usr/share}"

# Build if needed
cmake --build build -j$(nproc) > /dev/null 2>&1
if [ $? -ne 0 ]; then
    echo "❌ Build failed. Push aborted."
    exit 1
fi

# C++ tests
QT_QPA_PLATFORM=offscreen ./build/tests/logitune-tests --gtest_print_time=0 > /dev/null 2>&1
if [ $? -ne 0 ]; then
    echo "❌ C++ tests failed. Push aborted."
    QT_QPA_PLATFORM=offscreen ./build/tests/logitune-tests --gtest_print_time=0 2>&1 | grep FAILED
    exit 1
fi

# Tray tests
QT_QPA_PLATFORM=offscreen ./build/tests/logitune-tray-tests --gtest_print_time=0 > /dev/null 2>&1
if [ $? -ne 0 ]; then
    echo "❌ Tray tests failed. Push aborted."
    exit 1
fi

# QML tests
QT_QPA_PLATFORM=offscreen ./build/tests/qml/logitune-qml-tests > /dev/null 2>&1
if [ $? -ne 0 ]; then
    echo "❌ QML tests failed. Push aborted."
    exit 1
fi

# Extractor Python tests
(cd scripts && python3 -m pytest ../tests/scripts/test_extractor.py -q > /dev/null 2>&1)
if [ $? -ne 0 ]; then
    echo "❌ Extractor pytest failed. Push aborted."
    (cd scripts && python3 -m pytest ../tests/scripts/test_extractor.py -q 2>&1 | tail -20)
    exit 1
fi

echo "✅ All tests passed. Pushing..."
