name: Release

on:
  push:
    tags:
      - 'v*'

permissions:
  contents: write
  actions: read
  checks: read

jobs:
  release:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6
        with:
          fetch-depth: 0

      - name: Wait for CI (Build and Test)
        uses: lewagon/wait-on-check-action@v1.5.0
        with:
          ref: ${{ github.ref }}
          check-name: "Build and Test"
          repo-token: ${{ secrets.GITHUB_TOKEN }}
          wait-interval: 30

      - name: Wait for CI (WASM Dual Build)
        uses: lewagon/wait-on-check-action@v1.5.0
        with:
          ref: ${{ github.ref }}
          check-name: "WASM Dual Build"
          repo-token: ${{ secrets.GITHUB_TOKEN }}
          wait-interval: 30

      - name: Wait for CI (Benchmarks)
        uses: lewagon/wait-on-check-action@v1.5.0
        with:
          ref: ${{ github.ref }}
          check-name: "Benchmarks"
          repo-token: ${{ secrets.GITHUB_TOKEN }}
          wait-interval: 30

      - name: Generate Release Notes
        id: git-cliff
        uses: orhun/git-cliff-action@v4
        with:
          config: cliff.toml
          args: --latest --strip header
        env:
          OUTPUT: release_notes.md

      - name: Download CI Artifacts
        uses: dawidd6/action-download-artifact@v6
        with:
          github_token: ${{secrets.GITHUB_TOKEN}}
          workflow: ci.yml
          commit: ${{github.sha}}
          path: ./ci-artifacts

      - name: Package Artifacts
        run: |
          cd ci-artifacts
          zip -r ../wasm-package.zip wasm-package/
          zip -r ../benchmark-reports.zip benchmark-reports/
          cd ..

      - name: Create Release
        id: create_release
        uses: softprops/action-gh-release@v2
        with:
          tag_name: ${{ github.ref_name }}
          body_path: release_notes.md
          files: |
            wasm-package.zip
            benchmark-reports.zip
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

  publish-crates:
    needs: [release]
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6
      - name: Install Rust
        uses: dtolnay/rust-toolchain@stable
      - name: Publish to Crates.io
        run: cargo publish --token ${{ secrets.CRATES_TOKEN }} -p purecv

  publish-npm:
    needs: [release]
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6
      - name: Install Rust
        uses: dtolnay/rust-toolchain@stable
      - name: Install wasm-pack
        run: curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh
      - name: Build and Publish to NPM
        run: |
          npm run build:wasm
          cd crates/wasm/pkg
          npm config set //registry.npmjs.org/:_authToken ${{ secrets.NPM_TOKEN }}
          npm publish --access public