name: Andon CI - Test Health Monitoring

on:
  push:
    branches: [ master, main ]
  pull_request:
    branches: [ master, main ]

env:
  CARGO_TERM_COLOR: always

jobs:
  andon-red-alert:
    name: 🚨 Red Alert - Critical Failures
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3

      - name: Install Rust
        uses: actions-rs/toolchain@v1
        with:
          toolchain: stable
          override: true

      - name: Check Compilation (Red Alert)
        id: compilation
        run: |
          if ! cargo test --no-run 2>&1 | tee test_build.log; then
            echo "🚨 RED ALERT: Compilation failed"
            exit 1
          fi
          if grep -q "^error" test_build.log; then
            echo "🚨 RED ALERT: Compilation errors detected"
            cat test_build.log
            exit 1
          fi

      - name: Check Test Timeout (Red Alert)
        run: |
          if ! timeout 120 cargo test 2>&1 | tee test_run.log; then
            echo "🚨 RED ALERT: Tests exceeded 120s timeout"
            exit 1
          fi

      - name: Check Failure Rate (Red Alert)
        run: |
          TOTAL=$(grep -c "^test " test_run.log || echo 0)
          FAILED=$(grep -c "FAILED" test_run.log || echo 0)

          if [ "$TOTAL" -eq 0 ]; then
            echo "⚠️ WARNING: No tests found"
            exit 0
          fi

          FAIL_RATE=$(awk "BEGIN {printf \"%.1f\", ($FAILED / $TOTAL) * 100}")
          echo "Failure Rate: ${FAIL_RATE}%"

          if (( $(echo "$FAIL_RATE > 5.0" | bc -l) )); then
            echo "🚨 RED ALERT: ${FAIL_RATE}% tests failing (threshold: 5%)"
            exit 1
          fi

      - name: Upload Test Logs
        if: failure()
        uses: actions/upload-artifact@v3
        with:
          name: andon-red-alert-logs
          path: |
            test_build.log
            test_run.log

  andon-yellow-alert:
    name: ⚠️ Yellow Alert - Warnings
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3

      - name: Install Rust
        uses: actions-rs/toolchain@v1
        with:
          toolchain: stable
          override: true

      - name: Check for Flaky Tests (Yellow Alert)
        continue-on-error: true
        run: |
          # Get list of all tests
          TEST_LIST=$(cargo test --no-run 2>&1 | grep ": test$" | awk '{print $1}' || echo "")

          if [ -z "$TEST_LIST" ]; then
            echo "No tests found"
            exit 0
          fi

          FLAKY_COUNT=0

          # Sample first 10 tests to avoid timeout
          for test in $(echo "$TEST_LIST" | head -10); do
            PASS_COUNT=0

            for i in {1..3}; do
              if cargo test "$test" --quiet 2>/dev/null; then
                PASS_COUNT=$((PASS_COUNT + 1))
              fi
            done

            if [ $PASS_COUNT -gt 0 ] && [ $PASS_COUNT -lt 3 ]; then
              echo "⚠️ YELLOW ALERT: Flaky test detected: $test ($PASS_COUNT/3 passes)"
              FLAKY_COUNT=$((FLAKY_COUNT + 1))
            fi
          done

          if [ $FLAKY_COUNT -gt 0 ]; then
            echo "Total flaky tests: $FLAKY_COUNT"
          fi

      - name: Check Code Quality Warnings
        run: |
          cargo clippy --all-targets --all-features -- -D warnings 2>&1 | tee clippy.log || true

          WARNING_COUNT=$(grep -c "warning:" clippy.log || echo 0)

          if [ "$WARNING_COUNT" -gt 10 ]; then
            echo "⚠️ YELLOW ALERT: $WARNING_COUNT clippy warnings"
          fi

      - name: Upload Warning Logs
        if: always()
        uses: actions/upload-artifact@v3
        with:
          name: andon-yellow-alert-logs
          path: clippy.log

  andon-dashboard:
    name: 📊 Test Health Dashboard
    runs-on: ubuntu-latest
    needs: [andon-red-alert, andon-yellow-alert]
    if: always()
    steps:
      - uses: actions/checkout@v3

      - name: Install Rust
        uses: actions-rs/toolchain@v1
        with:
          toolchain: stable
          override: true

      - name: Generate Health Report
        run: |
          echo "═══════════════════════════════════════"
          echo "📊 TEST HEALTH DASHBOARD"
          echo "═══════════════════════════════════════"

          # Run tests and collect metrics
          cargo test 2>&1 | tee test_results.log

          TOTAL=$(grep -c "^test " test_results.log || echo 0)
          PASSED=$(grep -c "ok$" test_results.log || echo 0)
          FAILED=$(grep -c "FAILED" test_results.log || echo 0)

          if [ "$TOTAL" -gt 0 ]; then
            PASS_RATE=$(awk "BEGIN {printf \"%.1f\", ($PASSED / $TOTAL) * 100}")
            FAIL_RATE=$(awk "BEGIN {printf \"%.1f\", ($FAILED / $TOTAL) * 100}")
          else
            PASS_RATE="0.0"
            FAIL_RATE="0.0"
          fi

          echo "Total Tests:    $TOTAL"
          echo "✅ Passing:      $PASSED (${PASS_RATE}%)"
          echo "❌ Failing:      $FAILED (${FAIL_RATE}%)"
          echo "═══════════════════════════════════════"

          # Determine overall status
          if [ "$FAILED" -eq 0 ]; then
            echo "✅ GREEN: All tests passing"
            exit 0
          elif (( $(echo "$FAIL_RATE > 5.0" | bc -l) )); then
            echo "🚨 RED: High failure rate"
            exit 1
          else
            echo "⚠️ YELLOW: Some tests failing"
            exit 0
          fi

      - name: Create Summary
        if: always()
        run: |
          echo "## 📊 Test Health Report" >> $GITHUB_STEP_SUMMARY
          echo "" >> $GITHUB_STEP_SUMMARY
          echo "| Metric | Value |" >> $GITHUB_STEP_SUMMARY
          echo "|--------|-------|" >> $GITHUB_STEP_SUMMARY

          TOTAL=$(grep -c "^test " test_results.log || echo 0)
          PASSED=$(grep -c "ok$" test_results.log || echo 0)
          FAILED=$(grep -c "FAILED" test_results.log || echo 0)

          echo "| Total Tests | $TOTAL |" >> $GITHUB_STEP_SUMMARY
          echo "| ✅ Passing | $PASSED |" >> $GITHUB_STEP_SUMMARY
          echo "| ❌ Failing | $FAILED |" >> $GITHUB_STEP_SUMMARY
