#!/bin/bash

# script/test: Run project tests
#
# Runs pytest with project configuration. Automatically cleans up package
# installations after test run to prevent Home Assistant from loading the
# wrong version.
#
# Usage:
#   ./scripts/test [PYTEST_OPTIONS]
#
# Examples:
#   ./scripts/test
#   ./scripts/test -v
#   ./scripts/test -k test_midnight
#   ./scripts/test tests/test_cache_validity.py

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
cd "$SCRIPT_DIR/.."

# shellcheck source=scripts/.lib/output.sh
source "$SCRIPT_DIR/.lib/output.sh"

# Check if pytest is available
if ! .venv/bin/python -c "import pytest" 2>/dev/null; then
    log_info "pytest not found. Installing test dependencies..."
    uv pip install -e ".[test]"
fi

# Run pytest with project configuration
log_header "Running tests"
echo ""
.venv/bin/pytest "$@"

# Clean up any accidental package installation from pytest/test dependencies
# This prevents Home Assistant from loading the installed version instead of
# the development version from custom_components/
"$SCRIPT_DIR/clean" --minimal
