#!/usr/bin/env bash
# ──────────────────────────────────────────────────────────────────────
# collect_coverage.sh — Run flutter test --coverage and report results
#
# Usage:
#   ./tools/collect_coverage.sh           # Run from kell_creations_apps/
#
# Generates coverage/lcov.info per package, then prints a summary table
# showing test pass/fail counts and line coverage percentage.
#
# Exit codes:
#   0 — all tests passed
#   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
  apps/kell_web
)

OVERALL_EXIT=0

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

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

# ── Tests with coverage ─────────────────────────────────────────────
echo ""
echo "══════════════════════════════════════"
echo "  Running flutter test --coverage"
echo "══════════════════════════════════════"

declare -A RESULTS_PASS
declare -A RESULTS_FAIL
declare -A RESULTS_LH
declare -A RESULTS_LF
declare -A RESULTS_PCT

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

  TMPFILE=$(mktemp)
  if (cd "$ROOT_DIR/$pkg" && flutter test --coverage --reporter expanded 2>&1) | tee "$TMPFILE"; then
    : # tests passed
  else
    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"

  # Parse lcov.info for coverage
  LCOV="$ROOT_DIR/$pkg/coverage/lcov.info"
  if [ -f "$LCOV" ]; then
    LF=$(grep -oP '(?<=LF:)\d+' "$LCOV" | awk '{s+=$1} END {print s+0}')
    LH=$(grep -oP '(?<=LH:)\d+' "$LCOV" | awk '{s+=$1} END {print s+0}')
    if [ "$LF" -gt 0 ]; then
      PCT=$(awk "BEGIN {printf \"%.1f\", ($LH/$LF)*100}")
    else
      PCT="0.0"
    fi
  else
    LF=0
    LH=0
    PCT="—"
  fi
  RESULTS_LH[$NAME]=$LH
  RESULTS_LF[$NAME]=$LF
  RESULTS_PCT[$NAME]=$PCT
done

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

TOTAL_PASS=0
TOTAL_FAIL=0
TOTAL_HIT=0
TOTAL_FOUND=0

for pkg in "${TESTABLE[@]}"; do
  NAME=$(basename "$pkg")
  P=${RESULTS_PASS[$NAME]:-0}
  F=${RESULTS_FAIL[$NAME]:-0}
  LH=${RESULTS_LH[$NAME]:-0}
  LF=${RESULTS_LF[$NAME]:-0}
  PCT=${RESULTS_PCT[$NAME]:-"—"}

  if [ "$PCT" != "—" ]; then
    LINES="$LH/$LF"
    PCT_DISPLAY="${PCT}%"
  else
    LINES="—"
    PCT_DISPLAY="—"
  fi

  printf "║ %-20s %-7s %-7s %-8s %-10s ║\n" "$NAME" "$P" "$F" "$LINES" "$PCT_DISPLAY"
  TOTAL_PASS=$((TOTAL_PASS + P))
  TOTAL_FAIL=$((TOTAL_FAIL + F))
  TOTAL_HIT=$((TOTAL_HIT + LH))
  TOTAL_FOUND=$((TOTAL_FOUND + LF))
done

if [ "$TOTAL_FOUND" -gt 0 ]; then
  TOTAL_PCT=$(awk "BEGIN {printf \"%.1f\", ($TOTAL_HIT/$TOTAL_FOUND)*100}")
  TOTAL_LINES="$TOTAL_HIT/$TOTAL_FOUND"
  TOTAL_PCT_DISPLAY="${TOTAL_PCT}%"
else
  TOTAL_LINES="—"
  TOTAL_PCT_DISPLAY="—"
fi

echo "╠═══════════════════════════════════════════════════════════╣"
printf "║ %-20s %-7s %-7s %-8s %-10s ║\n" "TOTAL" "$TOTAL_PASS" "$TOTAL_FAIL" "$TOTAL_LINES" "$TOTAL_PCT_DISPLAY"
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."
  echo "📊 Overall line coverage: $TOTAL_PCT_DISPLAY ($TOTAL_LINES lines)"
fi

exit $OVERALL_EXIT
