name: CI

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

env:
  CARGO_TERM_COLOR: always

jobs:
  # Fast lint check - runs in parallel with coverage
  lint:
    name: Clippy & Format
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: dtolnay/rust-toolchain@stable
        with:
          components: rustfmt, clippy

      - uses: Swatinem/rust-cache@v2

      - name: Check formatting
        run: cargo fmt --all --check

      - name: Clippy
        run: cargo clippy --all-targets --all-features -- -D warnings

  # Coverage with tarpaulin (90% threshold enforced)
  coverage:
    name: 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-tarpaulin
        uses: taiki-e/install-action@v2
        with:
          tool: cargo-tarpaulin

      - name: Run coverage
        run: cargo tarpaulin --config tarpaulin.toml
        env:
          TEMP: ${{ runner.temp }}
          TMP: ${{ runner.temp }}

  # Self-check with freshly compiled sloc-guard (debug build for speed)
  sloc-guard-dev:
    name: SLOC Guard (Dev Build)
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0 # For --diff mode

      - uses: dtolnay/rust-toolchain@stable

      - uses: Swatinem/rust-cache@v2

      - name: Build sloc-guard (debug)
        run: cargo build

      - name: Run sloc-guard check
        run: |
          if [ -n "${{ github.event.pull_request.base.ref }}" ]; then
            ./target/debug/sloc-guard check --diff "origin/${{ github.event.pull_request.base.ref }}"
          else
            ./target/debug/sloc-guard check
          fi

  # Self-check with sloc-guard action (for SARIF upload)
  sloc-guard:
    name: SLOC Guard
    runs-on: ubuntu-latest
    permissions:
      contents: read
      security-events: write
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0 # For --diff mode

      - name: Run sloc-guard
        uses: doraemonkeys/sloc-guard/.github/action@master
        with:
          sarif-output: results.sarif
          diff: ${{ github.event.pull_request.base.ref && format('origin/{0}', github.event.pull_request.base.ref) || '' }}

      - name: Upload SARIF
        uses: github/codeql-action/upload-sarif@v4
        with:
          sarif_file: results.sarif
