name: Publish Binaries

on:
  workflow_run:
    workflows: [CI]
    types: [completed]

jobs:
  bin-publish:

    # can't use github.ref because of this bug: https://github.com/orgs/community/discussions/27124
    if: ${{ github.event.workflow_run.conclusion == 'success' && startsWith(github.event.workflow_run.head_branch, 'v') }}
    env:
      HEAD_TAG: ${{ github.event.workflow_run.head_branch }}

    runs-on: ubuntu-latest

    permissions:
      contents: read
      id-token: write # CRITICAL for provenance

    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Load variables from .env file
        run: cat .env >> $GITHUB_ENV

      - name: Verify version matches tag
        run: |
          # Extract tag version (remove 'v' prefix if present)
          TAG_VERSION="${HEAD_TAG#v}"

          # Get version from package.json
          PKG_VERSION=$(node -p "require('./package.json').version")

          echo "Git tag version: $TAG_VERSION"
          echo "Package.json version: $PKG_VERSION"

          # Compare versions
          if [ "$TAG_VERSION" != "$PKG_VERSION" ]; then
            echo "ERROR: Git tag version ($TAG_VERSION) does not match package.json version ($PKG_VERSION)"
            exit 1
          fi

          PKG_MINOR_PATCH="${PKG_VERSION#*.}"
          PI_MINOR_PATCH="${PI_VERSION#*.}"

          if [ "$PKG_MINOR_PATCH" != "$PI_MINOR_PATCH" ]; then
              echo "Minor and patch components of package.json version ($PKG_VERSION) are different from corresponding components of pi version ($PI_VERSION)"
              exit 1
          fi

          #echo "✓ Versions match!"

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '22'
          registry-url: 'https://registry.npmjs.org'

      - name: Check NPM version
        run: npm --version

      - name: Install dependencies
        run: npm install

      - name: Build
        run: npm run build

      - name: Publish awto-pi-lot to npm
        run: |
          # undo release mistake
          npm unpublish awto-pi-lot@2.74.0

          npm publish --provenance --access public
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
