#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
RESULTS_DIR="$PROJECT_ROOT/tests/test-results"
PERF_ONLY=false
UNIT_ONLY=false

for arg in "$@"; do
  case $arg in
    --unit-only) UNIT_ONLY=true ;;
    --perf-only) PERF_ONLY=true ;;
    --help|-h)
      echo "Usage: $0 [--unit-only] [--perf-only]"
      echo "  --unit-only   Run only unit/blackbox tests (skip performance)"
      echo "  --perf-only   Run only performance tests"
      exit 0
      ;;
  esac
done

cleanup() {
  if [ -d "$RESULTS_DIR" ]; then
    echo "Results saved to $RESULTS_DIR"
  fi
}
trap cleanup EXIT

mkdir -p "$RESULTS_DIR"

FAILED=0

if ! $PERF_ONLY; then
  echo "════════════════════════════════════"
  echo " Running blackbox + unit tests"
  echo "════════════════════════════════════"

  cd "$PROJECT_ROOT"

  if python -m pytest tests/ \
    --ignore=tests/performance/ \
    --tb=short \
    --junitxml="$RESULTS_DIR/test-results.xml" \
    -q; then
    echo "✓ Tests passed"
  else
    echo "✗ Tests failed"
    FAILED=1
  fi
fi

if ! $UNIT_ONLY; then
  echo ""
  echo "════════════════════════════════════"
  echo " Running performance tests"
  echo "════════════════════════════════════"

  cd "$PROJECT_ROOT"

  if python -m pytest tests/performance/ \
    --tb=short \
    --junitxml="$RESULTS_DIR/performance-results.xml" \
    -q 2>/dev/null; then
    echo "✓ Performance tests passed"
  else
    if [ -d "tests/performance" ]; then
      echo "✗ Performance tests failed"
      FAILED=1
    else
      echo "⊘ No performance test directory found — skipping"
    fi
  fi
fi

echo ""
echo "════════════════════════════════════"
echo " Summary"
echo "════════════════════════════════════"

if [ -f "$RESULTS_DIR/test-results.xml" ]; then
  TESTS=$(python -c "
import xml.etree.ElementTree as ET
t = ET.parse('$RESULTS_DIR/test-results.xml').getroot()
print(f\"Tests: {t.get('tests',0)}  Failures: {t.get('failures',0)}  Errors: {t.get('errors',0)}  Skipped: {t.get('skipped',0)}\")
" 2>/dev/null || echo "Could not parse test results XML")
  echo "$TESTS"
fi

if [ $FAILED -ne 0 ]; then
  echo "EXIT: 1 (failures detected)"
  exit 1
fi

echo "EXIT: 0 (all passed)"
exit 0
