name: Flutter Test

on:
  pull_request:
    branches:
      - main
  push:
    branches:
      - "**"
      - "!main"

jobs:
  test:
    name: Flutter Tests
    runs-on: ubuntu-latest
    container:
      image: ghcr.io/cirruslabs/flutter:stable

    defaults:
      run:
        working-directory: kell_creations_apps

    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Install dependencies — core
        run: cd packages/core && flutter pub get

      - name: Install dependencies — design_system
        run: cd packages/design_system && flutter pub get

      - name: Install dependencies — feature_wordpress
        run: cd packages/feature_wordpress && flutter pub get

      - name: Install dependencies — kell_web
        run: cd apps/kell_web && flutter pub get

      - name: Test with coverage — core
        run: |
          cd packages/core
          flutter test --coverage --reporter expanded 2>&1 | tee test_output.txt
          echo ""
          echo "=== core test summary ==="
          TOTAL=$(grep -cE '^\s*✓' test_output.txt || echo "0")
          FAILED=$(grep -cE '^\s*✗' test_output.txt || echo "0")
          echo "  Passed: $TOTAL"
          echo "  Failed: $FAILED"
          # Fail the step if any tests failed
          if [ "$FAILED" -gt 0 ]; then exit 1; fi

      - name: Test with coverage — design_system
        run: |
          cd packages/design_system
          flutter test --coverage --reporter expanded 2>&1 | tee test_output.txt
          echo ""
          echo "=== design_system test summary ==="
          TOTAL=$(grep -cE '^\s*✓' test_output.txt || echo "0")
          FAILED=$(grep -cE '^\s*✗' test_output.txt || echo "0")
          echo "  Passed: $TOTAL"
          echo "  Failed: $FAILED"
          if [ "$FAILED" -gt 0 ]; then exit 1; fi

      - name: Test with coverage — feature_wordpress
        run: |
          cd packages/feature_wordpress
          flutter test --coverage --reporter expanded 2>&1 | tee test_output.txt
          echo ""
          echo "=== feature_wordpress test summary ==="
          TOTAL=$(grep -cE '^\s*✓' test_output.txt || echo "0")
          FAILED=$(grep -cE '^\s*✗' test_output.txt || echo "0")
          echo "  Passed: $TOTAL"
          echo "  Failed: $FAILED"
          if [ "$FAILED" -gt 0 ]; then exit 1; fi

      - name: Test with coverage — kell_web
        run: |
          cd apps/kell_web
          flutter test --coverage --reporter expanded 2>&1 | tee test_output.txt
          echo ""
          echo "=== kell_web test summary ==="
          TOTAL=$(grep -cE '^\s*✓' test_output.txt || echo "0")
          FAILED=$(grep -cE '^\s*✗' test_output.txt || echo "0")
          echo "  Passed: $TOTAL"
          echo "  Failed: $FAILED"
          if [ "$FAILED" -gt 0 ]; then exit 1; fi

      - name: Aggregate test and coverage report
        if: always()
        run: |
          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 packages/core packages/design_system packages/feature_wordpress apps/kell_web; do
            NAME=$(basename "$pkg")
            OUTPUT="$pkg/test_output.txt"
            LCOV="$pkg/coverage/lcov.info"

            # Test counts
            if [ -f "$OUTPUT" ]; then
              PASS=$(grep -cE '^\s*✓' "$OUTPUT" || echo "0")
              FAIL=$(grep -cE '^\s*✗' "$OUTPUT" || echo "0")
            else
              PASS="—"
              FAIL="—"
            fi

            # Coverage from 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="N/A"
              fi
              LINES="$LH/$LF"
            else
              LINES="—"
              PCT="—"
              LF=0
              LH=0
            fi

            printf "║ %-20s %-7s %-7s %-8s %-10s ║\n" "$NAME" "$PASS" "$FAIL" "$LINES" "$PCT"

            if [ "$PASS" != "—" ]; then TOTAL_PASS=$((TOTAL_PASS + PASS)); fi
            if [ "$FAIL" != "—" ]; then TOTAL_FAIL=$((TOTAL_FAIL + FAIL)); fi
            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"
          else
            TOTAL_PCT="—"
            TOTAL_LINES="—"
          fi

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

          if [ "$TOTAL_FAIL" -gt 0 ]; then
            echo ""
            echo "❌ Some tests failed. See individual package results above."
            exit 1
          else
            echo ""
            echo "✅ All $TOTAL_PASS tests passed across all packages."
            echo "📊 Overall line coverage: $TOTAL_PCT ($TOTAL_LINES lines)"
          fi
