name: Release

on:
  push:
    tags:
      - 'v*'  # Trigger on version tags like v1.0.0, v0.0.1

permissions:
  contents: write

jobs:
  build:
    strategy:
      matrix:
        include:
          - runs-on: ubuntu-latest
            target: x86_64-unknown-linux-gnu
            artifact: leanKG-linux-x64.tar.gz
          - runs-on: macos-latest
            target: aarch64-apple-darwin
            artifact: leanKG-macos-arm64.tar.gz
          - runs-on: macos-latest
            target: x86_64-apple-darwin
            artifact: leanKG-macos-x64.tar.gz
          - runs-on: windows-latest
            target: x86_64-pc-windows-msvc
            artifact: leanKG-windows-x64.tar.gz
    runs-on: ${{ matrix.runs-on }}
    steps:
      - uses: actions/checkout@v4

      - name: Install Rust
        uses: dtolnay/rust-toolchain@stable
        with:
          targets: ${{ matrix.target }}

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

      - name: Package
        run: |
          mkdir -p release
          EXT=""
          if [ "${{ matrix.runs-on }}" = "windows-latest" ]; then
            EXT=".exe"
          fi
          cp target/${{ matrix.target }}/release/leankg$EXT release/leanKG
          tar -czf release/${{ matrix.artifact }} -C release leanKG
          rm release/leanKG
        shell: bash

      - uses: softprops/action-gh-release@v2
        with:
          tag_name: ${{ github.ref_name }}
          generate_release_notes: true
          files: release/${{ matrix.artifact }}

  publish:
    needs: build
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Install Rust
        uses: dtolnay/rust-toolchain@stable

      - name: Commit Cargo.lock
        run: |
          git config --local user.email "github-actions[bot]@users.noreply.github.com"
          git config --local user.name "github-actions[bot]"
          git add Cargo.lock
          git commit -m "chore: update Cargo.lock" || true

      - name: Publish to crates.io
        run: cargo publish --allow-dirty
        env:
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
