name: release

# Release flow: push a version tag (v0.2.0) to publish to npm AND create a
# visible GitHub Release. Bump package.json, commit, tag vX.Y.Z, push. The tag
# triggers both the npm publish and the GitHub Release, so every update is
# visible. If the version is already on npm (e.g. tagging an existing release),
# the publish step is skipped and only the GitHub Release is created.
on:
  push:
    tags:
      - 'v*'

jobs:
  publish:
    runs-on: ubuntu-latest
    permissions:
      contents: write
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4
        with:
          node-version: 20
          registry-url: https://registry.npmjs.org

      - name: Install dependencies
        run: npm install

      # Publish only when the tagged version is NEWER than npm's latest. A tag that
      # reaches GitHub late (git push --tags after the fact) must never publish an
      # old version as a fresh release.
      - name: Check if version is newer than the published one
        id: version
        run: |
          LOCAL=$(node -p "require('./package.json').version")
          PUBLISHED=$(npm view auto-model-router version 2>/dev/null || echo "0.0.0")
          echo "local=$LOCAL published=$PUBLISHED"
          NEWEST=$(printf '%s\n' "$PUBLISHED" "$LOCAL" | sort -V | tail -1)
          if [ "$LOCAL" != "$PUBLISHED" ] && [ "$NEWEST" = "$LOCAL" ]; then
            echo "changed=true" >> "$GITHUB_OUTPUT"
          else
            echo "changed=false" >> "$GITHUB_OUTPUT"
            echo "::warning::$LOCAL is not newer than the published $PUBLISHED; nothing published"
          fi

      - name: Publish to npm
        if: steps.version.outputs.changed == 'true'
        run: npm publish
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}

      - name: Create GitHub Release
        if: steps.version.outputs.changed == 'true'
        uses: softprops/action-gh-release@v2
        with:
          generate_release_notes: true
          name: auto-model-router ${{ github.ref_name }}
          body: |
            Published to npm as [`auto-model-router@${{ github.ref_name }}`](https://www.npmjs.com/package/auto-model-router).
            Install with `pi install npm:auto-model-router`.
