name: Build Desktop App

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

jobs:
  publish-npm:
    if: startsWith(github.ref, 'refs/tags/v')
    runs-on: ubuntu-latest
    permissions:
      contents: read
      id-token: write
    env:
      NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}

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

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

      - name: Install dependencies
        run: npm ci

      - name: Verify package version matches tag
        run: |
          node -e "const pkg=require('./package.json'); const tag=process.env.GITHUB_REF_NAME.replace(/^v/, ''); if (pkg.version !== tag) { console.error(`package.json version ${pkg.version} does not match tag ${tag}`); process.exit(1); }"

      - name: Release readiness checks
        run: npm run release:check

      - name: Show package version
        run: node -e "const pkg=require('./package.json'); console.log(`Preparing npm publish for ${pkg.name}@${pkg.version}`)"

      - name: Show latest published npm version
        run: npm view cligate version || echo "Package not found on npm yet"

      - name: Publish npm package
        run: |
          if [ -n "$NODE_AUTH_TOKEN" ]; then
            echo "Publishing with NPM_TOKEN"
            npm whoami
            npm publish --access public
          else
            echo "Publishing with npm trusted publishing"
            npm publish --access public --provenance
          fi

  build:
    strategy:
      matrix:
        include:
          - os: windows-latest
            platform: win
          - os: macos-latest
            platform: mac
          - os: ubuntu-latest
            platform: linux

    runs-on: ${{ matrix.os }}

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

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 24

      - name: Install dependencies
        run: npm ci

      - name: Build desktop app
        run: npx electron-builder --${{ matrix.platform }} --publish never
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Upload artifacts
        uses: actions/upload-artifact@v4
        with:
          name: cligate-${{ matrix.platform }}
          path: |
            dist-electron/*.exe
            dist-electron/*.dmg
            dist-electron/*.AppImage
          if-no-files-found: ignore

  release:
    needs: [publish-npm, build]
    if: startsWith(github.ref, 'refs/tags/v')
    runs-on: ubuntu-latest
    permissions:
      contents: write

    steps:
      - name: Download all artifacts
        uses: actions/download-artifact@v4
        with:
          path: artifacts

      - name: Create GitHub Release
        uses: softprops/action-gh-release@v2
        with:
          files: artifacts/**/*
          generate_release_notes: true
