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

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..."
