name: Release
on:
  workflow_run:
    workflows: ["Test the package"]
    branches: [main]
    types: [completed]
  workflow_dispatch:

jobs:
  check-version:
    name: Check version and create release
    runs-on: ubuntu-latest
    if: ${{ github.event_name == 'workflow_dispatch' || (github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.head_branch == 'main') }}
    permissions:
      contents: write

    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Extract version from Cargo.toml
        id: version
        run: |
          VERSION=$(grep '^version = ' Cargo.toml | head -1 | sed 's/version = "\(.*\)"/\1/')
          echo "version=v$VERSION" >> $GITHUB_OUTPUT
          echo "Version: v$VERSION"

      - name: Check if tag exists
        id: check_tag
        run: |
          if git rev-parse "${{ steps.version.outputs.version }}" >/dev/null 2>&1; then
            echo "exists=true" >> $GITHUB_OUTPUT
            echo "Tag ${{ steps.version.outputs.version }} already exists"
          else
            echo "exists=false" >> $GITHUB_OUTPUT
            echo "Tag ${{ steps.version.outputs.version }} does not exist"
          fi

      - name: Create tag
        if: steps.check_tag.outputs.exists == 'false'
        run: |
          git config user.name github-actions
          git config user.email github-actions@github.com
          git tag ${{ steps.version.outputs.version }}
          git push origin ${{ steps.version.outputs.version }}

      - name: Create GitHub Release
        if: steps.check_tag.outputs.exists == 'false'
        uses: softprops/action-gh-release@v1
        with:
          tag_name: ${{ steps.version.outputs.version }}
          name: Release ${{ steps.version.outputs.version }}
          draft: false
          prerelease: false
          generate_release_notes: true
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Install Rust
        if: steps.check_tag.outputs.exists == 'false'
        uses: dtolnay/rust-toolchain@stable

      - name: Publish to crates.io
        if: steps.check_tag.outputs.exists == 'false'
        run: cargo publish --features parametric,fft_tsne,gpu
        env:
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
