name: Manual Publish to npm

on:
  workflow_dispatch:

jobs:
  publish-npm:
    runs-on: ubuntu-latest
    permissions:
      id-token: write
      contents: write
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: "20.x"
          registry-url: "https://registry.npmjs.org"{{setupPmStep}}

      - name: Install, Build, and Test
        run: |
          {{installFrozen}}
          {{runBuild}}
          {{runTest}}

      - name: Commit dist directory (if changed)
        run: |
          git config --global user.name "github-actions[bot]"
          git config --global user.email "github-actions[bot]@users.noreply.github.com"
          git add dist
          # The following command creates a commit ONLY if there are staged changes.
          git diff --staged --quiet || git commit -m "chore: update build artifacts"
          git push

      - name: Publish to npm
        run: |
          VERSION=$(node -p "require('./package.json').version")
          # If version includes 'dev', publish with 'dev' tag, otherwise use 'latest'
          if echo "$VERSION" | grep -q 'dev'; then
            TAG=dev
          else
            TAG=latest
          fi
          npm publish --provenance --access public --tag "$TAG"
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}

      - name: Create and Push Git Tag
        run: |
          # This step now runs after the dist commit, ensuring the tag points to the correct commit.
          VERSION=$(node -p "require('./package.json').version")
          git tag "v$VERSION"
          git push origin "v$VERSION"
