name: Code Coverage

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

# Cancel in-progress runs when new commits are pushed
concurrency:
  group: "${{ github.workflow }}-${{ github.ref }}"
  cancel-in-progress: true

permissions:
  contents: read

env:
  CARGO_TERM_COLOR: always
  CARGO_PROFILE_DEV_DEBUG: line-tables-only

jobs:
  coverage:
    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v6

    - name: Install Rust
      uses: dtolnay/rust-toolchain@stable
      with:
        components: llvm-tools-preview

    - name: Cache Rust dependencies
      uses: Swatinem/rust-cache@v2

    - name: Install cargo-llvm-cov
      uses: taiki-e/install-action@v2
      with:
        tool: cargo-llvm-cov

    - name: Free up disk space
      run: |
        sudo rm -rf /usr/share/dotnet
        sudo rm -rf /usr/local/lib/android
        sudo rm -rf /opt/ghc
        sudo rm -rf /opt/hostedtoolcache/CodeQL
        sudo docker image prune --all --force
        df -h

    - name: Build debtmap binary
      run: cargo build --bin debtmap

    - name: Generate code coverage
      run: |
        cargo llvm-cov clean
        mkdir -p target/coverage
        cargo llvm-cov --all-features --json --output-path target/coverage/coverage.json
        cargo llvm-cov --all-features --html --output-dir target/coverage --no-clean
        COVERAGE=$(cat target/coverage/coverage.json | jq -r '.data[0].totals.lines.percent')
        echo "Current coverage: ${COVERAGE}%"

    - name: Archive code coverage results
      uses: actions/upload-artifact@v7
      with:
        name: code-coverage-report
        path: target/coverage/

    - name: Check coverage threshold
      run: |
        COVERAGE=$(cat target/coverage/coverage.json | jq -r '.data[0].totals.lines.percent')
        echo "Current coverage: ${COVERAGE}%"

        if (( $(echo "$COVERAGE < 80" | bc -l) )); then
          echo "⚠️  Coverage is below 80%: $COVERAGE%"
          exit 1
        else
          echo "✅ Coverage meets 80% threshold: $COVERAGE%"
        fi
