name: Debtmap

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

# 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
  RUST_BACKTRACE: 1

jobs:
  validate:
    name: Technical Debt Validation
    runs-on: ubuntu-latest

    steps:
    - name: Checkout repository
      uses: actions/checkout@v6
      with:
        fetch-depth: 0

    - name: Setup Rust
      uses: dtolnay/rust-toolchain@stable
      with:
        components: rustfmt, clippy, llvm-tools-preview

    - name: Cache Rust dependencies
      uses: Swatinem/rust-cache@v2
      with:
        cache-bin: "false"

    - name: Free disk space
      run: |
        echo "Disk space before cleanup:"
        df -h
        sudo rm -rf /usr/share/dotnet
        sudo rm -rf /usr/local/lib/android
        sudo rm -rf /opt/ghc
        sudo rm -rf /opt/hostedtoolcache/CodeQL
        echo "Disk space after cleanup:"
        df -h

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

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

    - name: Generate coverage data
      run: |
        mkdir -p target/coverage
        cargo llvm-cov clean
        SKIP_INTEGRATION_TESTS=1 cargo llvm-cov nextest --lcov --output-path target/coverage/lcov.info \
          --lib --test analyzer_tests --test complexity_tests --test core_metrics_tests \
          --test debt_tests --test entropy_tests \
          --status-level fail --final-status-level slow
        echo "Disk space after coverage generation:"
        df -h

    - name: Build debtmap release binary
      run: |
        cargo build --release
        echo "Disk space after release build:"
        df -h

    - name: Run debtmap validation with coverage
      run: |
        if [ -f "target/coverage/lcov.info" ]; then
          ./target/release/debtmap validate . --coverage-file target/coverage/lcov.info --format json --output debtmap-report.json --context
        else
          echo "Warning: LCOV file not found, running validation without coverage data"
          ./target/release/debtmap validate . --format json --output debtmap-report.json --context
        fi

    - name: Upload debtmap report and coverage
      if: always()
      uses: actions/upload-artifact@v7
      with:
        name: debtmap-analysis-artifacts
        path: |
          debtmap-report.json
          target/coverage/lcov.info
        retention-days: 7
