name: Rust CI

on:
  push:
    branches: [ "main" ]
  pull_request:
    branches: [ "main" ]

env:
  CARGO_TERM_COLOR: always
  RUST_BACKTRACE: 1

jobs:
  # Format checking
  fmt:
    name: Rustfmt
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
      - uses: dtolnay/rust-toolchain@67ef31d5b988238dd797d409d6f9574278e20537 # master
        with:
          toolchain: stable
          components: rustfmt
      - name: Check formatting
        run: cargo fmt -- --check

  # Linting with Clippy — `-D warnings` makes lint regressions fail CI.
  clippy:
    name: Clippy
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
      - uses: dtolnay/rust-toolchain@67ef31d5b988238dd797d409d6f9574278e20537 # master
        with:
          toolchain: stable
          components: clippy
      - uses: Swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32 # v2
      - name: Run clippy
        run: cargo clippy --all-targets -- -D warnings

  # Build and test on multiple Rust versions and OS
  test:
    name: Test Suite
    runs-on: ${{ matrix.os }}
    strategy:
      fail-fast: false
      matrix:
        os: [ubuntu-latest, macos-latest, windows-latest]
        rust: [stable, beta]
        include:
          # Test nightly only on Linux to save CI time
          - os: ubuntu-latest
            rust: nightly
    steps:
      - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0

      - name: Install Rust toolchain
        uses: dtolnay/rust-toolchain@67ef31d5b988238dd797d409d6f9574278e20537 # master
        with:
          toolchain: ${{ matrix.rust }}

      # Cache dependencies for faster builds
      - uses: Swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32 # v2
        with:
          # Cache key includes OS and Rust version
          key: ${{ matrix.os }}-${{ matrix.rust }}

      - name: Build
        run: cargo build --verbose

      - name: Run tests
        run: cargo test --verbose

      # Only check documentation on stable Linux
      - name: Check documentation
        if: matrix.rust == 'stable' && matrix.os == 'ubuntu-latest'
        run: cargo doc --no-deps --document-private-items

  # Security audit
  security:
    name: Security Audit
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
      - uses: rustsec/audit-check@69366f33c96575abad1ee0dba8212993eecbe998 # v2
        with:
          token: ${{ secrets.GITHUB_TOKEN }}