#!/usr/bin/env bash
# ═══════════════════════════════════════════════════════════════════════
# typecheck-all.sh — Run TypeScript typecheck 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
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
)

# Subdirectories that may have their own typecheck script
SUBS=(backend web user-dashboard-web mindlyst-native/web)

echo ""
echo -e "${BOLD}╔═══════════════════════════════════════════════════════════╗${NC}"
echo -e "${BOLD}║       ByteLyst Cross-Repo Typecheck                       ║${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_tc=$(jq -r '.scripts.typecheck // empty' "$pkg" 2>/dev/null)
    [ -n "$has_tc" ] || continue

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

    if (cd "${repo_dir}/${sub}" && pnpm run typecheck 2>&1) > /tmp/tc-output-$$.txt 2>&1; then
      echo -e "\r  ${GREEN}✓${NC} ${label}"
      PASS=$((PASS + 1))
    else
      echo -e "\r  ${RED}✗${NC} ${label}"
      tail -5 /tmp/tc-output-$$.txt | while IFS= read -r line; do echo "    ${line}"; done
      FAIL=$((FAIL + 1))
      FAILURES+=("$label")
    fi
    rm -f /tmp/tc-output-$$.txt
  done
done

echo ""
echo -e "${BOLD}═══ Summary ═══${NC}"
echo -e "  ${GREEN}Passed:${NC}  ${PASS}"
echo -e "  ${RED}Failed:${NC}  ${FAIL}"

if [ $FAIL -gt 0 ]; then
  echo ""
  echo -e "${RED}${BOLD}FAILED${NC} — ${FAIL} typecheck(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} typecheck(s) clean."
  exit 0
fi
