#!/bin/bash

# Script to run simplified tests with environment awareness
echo "Starting simplified test suite execution..."

# Set test environment
if [[ "$1" == "staging" ]]; then
    export HVAC_ENV=staging
    echo "Running tests in staging environment mode"
else
    echo "Running tests in local environment mode"
fi

# Ensure we're in the correct directory
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd "$SCRIPT_DIR/.."

# Determine PHPUnit command
if command -v phpunit &> /dev/null; then
    PHPUNIT_CMD="phpunit"
else
    if [ -f "./vendor/bin/phpunit" ]; then
        PHPUNIT_CMD="./vendor/bin/phpunit"
    else
        echo "PHPUnit not found. Installing PHPUnit..."
        composer require --dev phpunit/phpunit
        PHPUNIT_CMD="./vendor/bin/phpunit"
    fi
fi

echo "Using PHPUnit command: $PHPUNIT_CMD"

# Create test results directory if it doesn't exist
mkdir -p tests/test-results/simplified

# Run tests in specific order with detailed logging
echo "Running utility function tests..."
$PHPUNIT_CMD --testdox \
    --log-junit tests/test-results/simplified/utils.xml \
    tests/basic/test-utils.php

echo "Running hooks and filters tests..."
$PHPUNIT_CMD --testdox \
    --log-junit tests/test-results/simplified/hooks.xml \
    tests/basic/test-hooks.php

echo "Running database operation tests..."
$PHPUNIT_CMD --testdox \
    --log-junit tests/test-results/simplified/db.xml \
    tests/basic/test-db.php

# Combine test results
echo "Generating combined test report..."
echo "Simplified Test Results" > tests/test-results/simplified/summary.txt
echo "======================" >> tests/test-results/simplified/summary.txt
echo "" >> tests/test-results/simplified/summary.txt

for result in tests/test-results/simplified/*.xml; do
    if [ -f "$result" ]; then
        echo "Results from $(basename "$result" .xml):" >> tests/test-results/simplified/summary.txt
        grep "testcase" "$result" | wc -l | xargs -I {} echo "Total tests: {}" >> tests/test-results/simplified/summary.txt
        grep "failure" "$result" | wc -l | xargs -I {} echo "Failures: {}" >> tests/test-results/simplified/summary.txt
        echo "" >> tests/test-results/simplified/summary.txt
    fi
done

# Display results
cat tests/test-results/simplified/summary.txt

echo "Test execution complete. Detailed results available in tests/test-results/simplified/"