#!/usr/bin/env bash
# ═══════════════════════════════════════════════════════════════════════
# test-all.sh — Run Vitest across all ByteLyst repos
# ═══════════════════════════════════════════════════════════════════════
set -euo pipefail

RED='\033[0;31m'; GREEN='\033[0;32m'; CYAN='\033[0;36m'
BOLD='\033[1m'; DIM='\033[2m'; NC='\033[0m'

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
WORKSPACE_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"

PASS=0
FAIL=0
SKIP=0
FAILURES=()

REPOS=(
  learning_ai_common_plat
  learning_voice_ai_agent
  learning_multimodal_memory_agents
  learning_ai_clock
  learning_ai_jarvis_jr
  learning_ai_fastgap
  learning_ai_peakpulse
  learning_ai_flowmonk
  learning_ai_notes
  learning_ai_trails
  learning_ai_local_memory_gpt
)

SUBS=(backend web user-dashboard-web mindlyst-native/web)

echo ""
echo -e "${BOLD}╔═══════════════════════════════════════════════════════════╗${NC}"
echo -e "${BOLD}║       ByteLyst Cross-Repo Test Runner                     ║${NC}"
echo -e "${BOLD}╚═══════════════════════════════════════════════════════════╝${NC}"
echo ""

for repo in "${REPOS[@]}"; do
  repo_dir="${WORKSPACE_ROOT}/${repo}"
  [ -d "$repo_dir" ] || continue

  for sub in "${SUBS[@]}"; do
    pkg="${repo_dir}/${sub}/package.json"
    [ -f "$pkg" ] || continue

    has_test=$(jq -r '.scripts.test // empty' "$pkg" 2>/dev/null)
    [ -n "$has_test" ] || continue

    # Check if there are actually test files
    test_count=$(find "${repo_dir}/${sub}/src" -name '*.test.ts' -o -name '*.test.tsx' 2>/dev/null | head -1)
    if [ -z "$test_count" ]; then
      SKIP=$((SKIP + 1))
      continue
    fi

    label="${repo}/${sub}"
    echo -ne "  ${CYAN}▶${NC} ${label}..."

    if (cd "${repo_dir}/${sub}" && pnpm run test --run 2>&1) > /tmp/test-output-$$.txt 2>&1; then
      # Extract test count from vitest output
      summary=$(grep -E 'Tests\s+[0-9]' /tmp/test-output-$$.txt 2>/dev/null | tail -1 || echo "")
      echo -e "\r  ${GREEN}✓${NC} ${label} ${DIM}${summary}${NC}"
      PASS=$((PASS + 1))
    else
      echo -e "\r  ${RED}✗${NC} ${label}"
      grep -E 'FAIL|Error|failed' /tmp/test-output-$$.txt 2>/dev/null | tail -5 | while IFS= read -r line; do echo "    ${line}"; done
      FAIL=$((FAIL + 1))
      FAILURES+=("$label")
    fi
    rm -f /tmp/test-output-$$.txt
  done
done

echo ""
echo -e "${BOLD}═══ Summary ═══${NC}"
echo -e "  ${GREEN}Passed:${NC}  ${PASS}"
echo -e "  ${RED}Failed:${NC}  ${FAIL}"
if [ $SKIP -gt 0 ]; then
  echo -e "  ${DIM}Skipped: ${SKIP} (no test files)${NC}"
fi

if [ $FAIL -gt 0 ]; then
  echo ""
  echo -e "${RED}${BOLD}FAILED${NC} — ${FAIL} test suite(s) failed:"
  for f in "${FAILURES[@]}"; do
    echo -e "  ${RED}✗${NC} ${f}"
  done
  exit 1
else
  echo ""
  echo -e "${GREEN}${BOLD}ALL PASSED${NC} — ${PASS} suite(s) green."
  exit 0
fi
