name: Rust build

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

env:
  CARGO_TERM_COLOR: always

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Cache cargo registry
        uses: actions/cache@v4
        with:
          path: |
            ~/.cargo/registry
            ~/.cargo/git
          key: ${{ runner.os }}-cargo-registry-${{ hashFiles('**/Cargo.lock') }}
      - name: Cache cargo build
        uses: actions/cache@v4
        with:
          path: target
          key: ${{ runner.os }}-cargo-build-${{ hashFiles('**/Cargo.lock') }}
      - name: Install stable toolchain
        uses: dtolnay/rust-toolchain@stable
      - name: Build project
        run: cargo build

  test:
    runs-on: ubuntu-latest
    needs: build
    steps:
      - uses: actions/checkout@v4
      - name: Cache cargo registry
        uses: actions/cache@v4
        with:
          path: |
            ~/.cargo/registry
            ~/.cargo/git
          key: ${{ runner.os }}-cargo-registry-${{ hashFiles('**/Cargo.lock') }}
      - name: Cache cargo build
        uses: actions/cache@v4
        with:
          path: target
          key: ${{ runner.os }}-cargo-build-${{ hashFiles('**/Cargo.lock') }}
      - name: Install stable toolchain
        uses: dtolnay/rust-toolchain@stable
      - name: Run tests
        run: cargo test --all

  check-spdx:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Check SPDX headers in Rust files
        run: |
          missing_files=""
          for file in $(find src -name '*.rs'); do
            if ! grep -q '^// SPDX-License-Identifier: MIT' "$file"; then
              echo "Missing SPDX header in $file"
              missing_files="$missing_files\n$file"
            fi
          done
          if [ -n "$missing_files" ]; then
            echo "\nSummary: The following files are missing SPDX headers:"
            echo -e "$missing_files"
            exit 1
          fi
