name: Release

on:
  push:
    tags:
      - 'v*.*.*'

permissions:
  contents: write   # create GitHub Release
  id-token: write   # npm OIDC Trusted Publishing

jobs:
  verify:
    name: Verify
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: dtolnay/rust-toolchain@stable
        with:
          components: clippy, rustfmt
          targets: wasm32-unknown-unknown
      - uses: Swatinem/rust-cache@v2
      - run: cargo test --workspace
      - run: cargo clippy --all-targets -- -D warnings
      - run: cargo fmt --check

  github-release:
    name: GitHub Release
    needs: verify
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Extract release notes from CHANGELOG
        run: |
          VERSION="${GITHUB_REF_NAME#v}"
          awk -v ver="$VERSION" '
            $0 ~ "^## \\[" ver "\\]" { found=1; next }
            found && /^## \[/ { exit }
            found { print }
          ' CHANGELOG.md > release_notes.md
      - name: Create GitHub Release
        run: |
          gh release create "${{ github.ref_name }}" \
            --title "${{ github.ref_name }}" \
            --notes-file release_notes.md
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}

  publish-crates-io:
    name: Publish crates.io
    needs: verify
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: dtolnay/rust-toolchain@stable
      - uses: Swatinem/rust-cache@v2
      - name: Publish syllabify-fr
        run: cargo publish -p syllabify-fr --token ${{ secrets.CARGO_REGISTRY_TOKEN }}

  publish-npm:
    name: Publish @dyscolor/syllabify-fr-wasm
    needs: verify
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: dtolnay/rust-toolchain@stable
        with:
          targets: wasm32-unknown-unknown
      - uses: Swatinem/rust-cache@v2
      - name: Install wasm-pack
        run: curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh
      - name: Build WASM
        run: wasm-pack build wasm/ --target bundler --scope dyscolor --release
      - uses: actions/setup-node@v4
        with:
          node-version: '24'   # ships with npm 11.x natively (required for OIDC)
          # No registry-url: prevents setup-node from injecting NODE_AUTH_TOKEN,
          # which would shadow the OIDC credentials.
      - name: Verify npm version (>= 11.5.1 required for OIDC trusted publishing)
        run: |
          npm --version
          npm --version | awk -F. '{ if ($1 < 11 || ($1 == 11 && $2 < 5)) { print "npm >= 11.5.1 required for OIDC, got " $0 > "/dev/stderr"; exit 1 } }'
      - name: Publish to npm
        working-directory: wasm/pkg
        run: npm publish --access public --provenance
        env:
          NODE_AUTH_TOKEN: ""  # clear in case setup-node injected one
