name: Coverage Analysis

on:
  workflow_run:
    workflows: [CI]
    types: [completed]
    branches: [master, main]

jobs:
  # Generate additional coverage analysis if CI passed
  coverage-analysis:
    name: Coverage Analysis
    runs-on: ubuntu-latest
    if: github.event.workflow_run.conclusion == 'success'
    
    steps:
    - name: Checkout code
      uses: actions/checkout@v4
    
    - name: Set up Go
      uses: actions/setup-go@v5
      with:
        go-version: '1.23'
    
    - name: Download coverage artifacts
      uses: actions/download-artifact@v4
      with:
        name: coverage-report
        run-id: ${{ github.event.workflow_run.id }}
        github-token: ${{ secrets.GITHUB_TOKEN }}
    
    - name: Check coverage percentage
      run: |
        if [ -f coverage.out ]; then
          echo "📊 Coverage Report:"
          go tool cover -func=coverage.out | tail -1
          
          coverage=$(go tool cover -func=coverage.out | grep total | awk '{print $3}' | sed 's/%//')
          echo "Total Coverage: ${coverage}%"
          
          # Set threshold to 50%
          threshold=50
          if (( $(echo "$coverage < $threshold" | bc -l) )); then
            echo "⚠️  Coverage below ${threshold}% threshold: ${coverage}%"
            echo "::warning::Coverage is below ${threshold}% threshold"
          else
            echo "✅ Coverage above ${threshold}% threshold: ${coverage}%"
          fi
          
          # Generate detailed coverage by package
          echo ""
          echo "📦 Coverage by Package:"
          go tool cover -func=coverage.out | grep -E "^github.com" | sort -k3 -nr | head -20
        else
          echo "❌ Coverage file not found"
          exit 1
        fi
    
    - name: Comment PR with coverage
      if: github.event.workflow_run.event == 'pull_request'
      uses: marocchino/sticky-pull-request-comment@v2
      with:
        recreate: true
        message: |
          ## 📊 Coverage Report
          
          Total Coverage: **${{ steps.coverage.outputs.percentage }}%**
          
          [View detailed coverage report](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.event.workflow_run.id }})
