name: Rust - Build, test and publish
on:
  push:
    branches: [ "master" ]
    tags: ['v*']  # Triggers when pushing tags starting with 'v'
  pull_request:
    branches: [ "master" ]

env:
  CARGO_TERM_COLOR: always

jobs:
  build:
    strategy:
      matrix:
        include:
          - os: ubuntu-latest
            target: x86_64-unknown-linux-gnu
            artifact_name: sentencex
            asset_name: sentencex-linux-amd64
          - os: windows-latest
            target: x86_64-pc-windows-msvc
            artifact_name: sentencex.exe
            asset_name: sentencex-windows-amd64.exe
          - os: macos-latest
            target: x86_64-apple-darwin
            artifact_name: sentencex
            asset_name: sentencex-macos-amd64
          - os: macos-latest
            target: aarch64-apple-darwin
            artifact_name: sentencex
            asset_name: sentencex-macos-arm64

    runs-on: ${{ matrix.os }}

    steps:
    - uses: actions/checkout@v4

    - name: Setup Rust
      run: |
        rustup update stable
        rustup default stable
        rustup target add ${{ matrix.target }}

    - name: Build
      run: cargo build --release --target ${{ matrix.target }} --verbose

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

    - name: Upload artifacts
      uses: actions/upload-artifact@v4
      with:
        name: ${{ matrix.asset_name }}
        path: target/${{ matrix.target }}/release/${{ matrix.artifact_name }}
        if-no-files-found: error
  publish:
    runs-on: ubuntu-latest
    if: startsWith(github.ref, 'refs/tags/v')
    needs: build
    environment: release  # Optional: for enhanced security
    permissions:
      id-token: write     # Required for OIDC token exchange
    steps:
    - uses: actions/checkout@v5
    - uses: rust-lang/crates-io-auth-action@v1
      id: auth
    - run: cargo publish
      env:
        CARGO_REGISTRY_TOKEN: ${{ steps.auth.outputs.token }}
