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

PATH="$HOME/.npm-global/bin:$PATH"

SHORT=false
FILTER=""

while [[ $# -gt 0 ]]; do
  case "$1" in
    --short|-s) SHORT=true; shift ;;
    --filter|-f) FILTER="$2"; shift 2 ;;
    *) echo "Usage: tests.sh [--short|-s] [--filter|-f <package>]"; exit 1 ;;
  esac
done

strip_ansi() {
  sed $'s/\033\[[0-9;]*m//g'
}

run_tests() {
  local pkg="$1"
  local label="$2"

  if $SHORT; then
    local tmpfile
    tmpfile=$(mktemp)
    trap "rm -f $tmpfile" RETURN

    local exit_code=0
    pnpm --filter "$pkg" test:run >"$tmpfile" 2>&1 || exit_code=$?

    # Parse from cleaned output
    local clean
    clean=$(strip_ansi < "$tmpfile")

    local tests_line files_line duration_line
    tests_line=$(echo "$clean" | grep -oP 'Tests\s+\K.*' | tail -1 | xargs)
    files_line=$(echo "$clean" | grep -oP 'Test Files\s+\K.*' | tail -1 | xargs)
    duration_line=$(echo "$clean" | grep -oP 'Duration\s+\K[0-9.]+s' | tail -1)

    if [[ $exit_code -eq 0 ]]; then
      printf "  \033[32mPASS\033[0m  %-6s %s | %s | %s\n" "$label" "$files_line" "$tests_line" "$duration_line"
    else
      printf "  \033[31mFAIL\033[0m  %-6s %s | %s | %s\n" "$label" "$files_line" "$tests_line" "$duration_line"
      echo "$clean" | grep -E 'FAIL |AssertionError|expected .* to' | head -10 | sed 's/^/         /'
    fi

    rm -f "$tmpfile"
    return $exit_code
  else
    echo "=== $label ==="
    pnpm --filter "$pkg" test:run
    echo ""
  fi
}

if $SHORT; then
  echo "Running tests..."
  echo ""
fi

failed=0

if [[ -z "$FILTER" || "$FILTER" == "mcpd" ]]; then
  run_tests mcpd "mcpd" || failed=1
fi

if [[ -z "$FILTER" || "$FILTER" == "cli" ]]; then
  run_tests cli "cli" || failed=1
fi

if $SHORT; then
  echo ""
  if [[ $failed -eq 0 ]]; then
    echo "All tests passed."
  else
    echo "Some tests FAILED."
  fi
fi

exit $failed
