name: Coverage

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

env:
  CARGO_TERM_COLOR: always
  RUST_BACKTRACE: 1

jobs:
  coverage:
    name: Code Coverage
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      
      - uses: dtolnay/rust-toolchain@stable
        with:
          components: llvm-tools-preview
      
      - uses: Swatinem/rust-cache@v2
      
      - name: Install cargo-llvm-cov
        run: cargo install cargo-llvm-cov
      
      - name: Generate coverage
        run: |
          cargo llvm-cov clean --workspace
          cargo llvm-cov \
            --all-features \
            --workspace \
            --lcov \
            --output-path lcov.info \
            --ignore-filename-regex "tests/|benches/|examples/"
      
      - name: Upload coverage to Codecov
        uses: codecov/codecov-action@v3
        with:
          files: ./lcov.info
          fail_ci_if_error: true
      
      - name: Check coverage threshold
        run: |
          COVERAGE=$(cargo llvm-cov --summary-only --all-features --workspace 2>&1 | grep "TOTAL" | awk '{print $10}' | sed 's/%//')
          echo "Coverage: ${COVERAGE}%"
          if (( $(echo "$COVERAGE < 80" | bc -l) )); then
            echo "Coverage is below 80% threshold!"
            exit 1
          fi
          echo "Coverage meets the 80% threshold!"