#!/usr/bin/env bash
# ──────────────────────────────────────────────────────────────────────
# run_all_tests.sh — Run flutter test for all testable packages and apps
#
# Usage:
#   ./tools/run_all_tests.sh           # Run from kell_creations_apps/
#   ./tools/run_all_tests.sh --analyze # Also run dart analyze first
#
# Exit codes:
#   0 — all tests passed (and analyze clean, if requested)
#   1 — one or more failures
# ──────────────────────────────────────────────────────────────────────
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
ROOT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"

# Packages/apps with tests (add new ones here as they gain tests)
TESTABLE=(
  packages/core
  packages/design_system
  packages/feature_wordpress
  packages/feature_inventory
  packages/feature_orders
  apps/kell_web
  apps/kell_mobile
)

# All packages/apps to analyze (includes those without tests)
ANALYZABLE=(
  packages/core
  packages/design_system
  packages/feature_wordpress
  packages/feature_inventory
  packages/feature_orders
  packages/feature_policy
  apps/kell_web
  apps/kell_mobile
)

RUN_ANALYZE=false
if [[ "${1:-}" == "--analyze" ]]; then
  RUN_ANALYZE=true
fi

OVERALL_EXIT=0

# ── Dependency install ───────────────────────────────────────────────
echo ""
echo "══════════════════════════════════════"
echo "  Installing dependencies"
echo "══════════════════════════════════════"

for pkg in "${ANALYZABLE[@]}"; do
  echo "  → $pkg"
  (cd "$ROOT_DIR/$pkg" && flutter pub get --no-example) > /dev/null 2>&1
done

# ── Analyze (optional) ──────────────────────────────────────────────
if $RUN_ANALYZE; then
  echo ""
  echo "══════════════════════════════════════"
  echo "  Running dart analyze"
  echo "══════════════════════════════════════"

  ANALYZE_FAILURES=()
  for pkg in "${ANALYZABLE[@]}"; do
    NAME=$(basename "$pkg")
    printf "  %-25s" "$NAME"
    if (cd "$ROOT_DIR/$pkg" && dart analyze --fatal-infos) > /dev/null 2>&1; then
      echo "✅ clean"
    else
      echo "❌ issues found"
      ANALYZE_FAILURES+=("$NAME")
      OVERALL_EXIT=1
    fi
  done

  if [ ${#ANALYZE_FAILURES[@]} -gt 0 ]; then
    echo ""
    echo "  ❌ Analyze failures: ${ANALYZE_FAILURES[*]}"
  else
    echo ""
    echo "  ✅ All packages analyze clean"
  fi
fi

# ── Tests ────────────────────────────────────────────────────────────
echo ""
echo "══════════════════════════════════════"
echo "  Running flutter test"
echo "══════════════════════════════════════"

declare -A RESULTS_PASS
declare -A RESULTS_FAIL
TEST_FAILURES=()

for pkg in "${TESTABLE[@]}"; do
  NAME=$(basename "$pkg")
  echo ""
  echo "  ── $NAME ──"

  TMPFILE=$(mktemp)
  if (cd "$ROOT_DIR/$pkg" && flutter test --reporter expanded 2>&1) | tee "$TMPFILE"; then
    : # tests passed
  else
    TEST_FAILURES+=("$NAME")
    OVERALL_EXIT=1
  fi

  PASS=$(grep -cE '^\s*✓' "$TMPFILE" 2>/dev/null || echo "0")
  FAIL=$(grep -cE '^\s*✗' "$TMPFILE" 2>/dev/null || echo "0")
  RESULTS_PASS[$NAME]=$PASS
  RESULTS_FAIL[$NAME]=$FAIL
  rm -f "$TMPFILE"
done

# ── Summary ──────────────────────────────────────────────────────────
echo ""
echo "╔══════════════════════════════════════╗"
echo "║     Flutter Test Results Summary     ║"
echo "╠══════════════════════════════════════╣"
echo "║ Package              Pass    Fail    ║"
echo "╠══════════════════════════════════════╣"

TOTAL_PASS=0
TOTAL_FAIL=0

for pkg in "${TESTABLE[@]}"; do
  NAME=$(basename "$pkg")
  P=${RESULTS_PASS[$NAME]:-0}
  F=${RESULTS_FAIL[$NAME]:-0}
  printf "║ %-20s %-7s %-7s ║\n" "$NAME" "$P" "$F"
  TOTAL_PASS=$((TOTAL_PASS + P))
  TOTAL_FAIL=$((TOTAL_FAIL + F))
done

echo "╠══════════════════════════════════════╣"
printf "║ %-20s %-7s %-7s ║\n" "TOTAL" "$TOTAL_PASS" "$TOTAL_FAIL"
echo "╚══════════════════════════════════════╝"

if [ $OVERALL_EXIT -ne 0 ]; then
  echo ""
  echo "❌ Failures detected. See details above."
else
  echo ""
  echo "✅ All $TOTAL_PASS tests passed across all packages."
fi

exit $OVERALL_EXIT
