name: Plugin NPM Release

on:
  push:
    branches:
      - main
    paths:
      - ".github/workflows/plugin-npm-release.yml"
      - "extensions/**"
      - "package.json"
      - "scripts/lib/plugin-npm-release.ts"
      - "scripts/plugin-npm-publish.sh"
      - "scripts/plugin-npm-release-check.ts"
      - "scripts/plugin-npm-release-plan.ts"
  workflow_dispatch:
    inputs:
      publish_scope:
        description: Publish the selected plugins or all publishable plugins from the ref
        required: true
        default: selected
        type: choice
        options:
          - selected
          - all-publishable
      ref:
        description: Commit SHA on main to publish from (copy from the preview run)
        required: true
        type: string
      plugins:
        description: Comma-separated plugin package names to publish when publish_scope=selected
        required: false
        type: string

concurrency:
  group: plugin-npm-release-${{ github.event_name == 'workflow_dispatch' && inputs.ref || github.sha }}
  cancel-in-progress: false

env:
  FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: "true"
  NODE_VERSION: "24.x"
  PNPM_VERSION: "10.23.0"

jobs:
  preview_plugins_npm:
    runs-on: ubuntu-latest
    permissions:
      contents: read
    outputs:
      ref_sha: ${{ steps.ref.outputs.sha }}
      has_candidates: ${{ steps.plan.outputs.has_candidates }}
      candidate_count: ${{ steps.plan.outputs.candidate_count }}
      matrix: ${{ steps.plan.outputs.matrix }}
    steps:
      - name: Checkout
        uses: actions/checkout@v6
        with:
          ref: ${{ github.event_name == 'workflow_dispatch' && inputs.ref || github.sha }}
          fetch-depth: 0

      - name: Setup Node environment
        uses: ./.github/actions/setup-node-env
        with:
          node-version: ${{ env.NODE_VERSION }}
          pnpm-version: ${{ env.PNPM_VERSION }}
          install-bun: "false"
          use-sticky-disk: "false"

      - name: Resolve checked-out ref
        id: ref
        run: echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT"

      - name: Validate ref is on main
        run: |
          set -euo pipefail
          git fetch --no-tags origin +refs/heads/main:refs/remotes/origin/main
          git merge-base --is-ancestor HEAD origin/main

      - name: Validate publishable plugin metadata
        env:
          PUBLISH_SCOPE: ${{ github.event_name == 'workflow_dispatch' && inputs.publish_scope || '' }}
          RELEASE_PLUGINS: ${{ github.event_name == 'workflow_dispatch' && inputs.plugins || '' }}
          BASE_REF: ${{ github.event_name != 'workflow_dispatch' && github.event.before || '' }}
          HEAD_REF: ${{ steps.ref.outputs.sha }}
        run: |
          set -euo pipefail
          if [[ -n "${PUBLISH_SCOPE}" ]]; then
            release_args=(--selection-mode "${PUBLISH_SCOPE}")
            if [[ -n "${RELEASE_PLUGINS}" ]]; then
              release_args+=(--plugins "${RELEASE_PLUGINS}")
            fi
            pnpm release:plugins:npm:check -- "${release_args[@]}"
          elif [[ -n "${BASE_REF}" ]]; then
            pnpm release:plugins:npm:check -- --base-ref "${BASE_REF}" --head-ref "${HEAD_REF}"
          else
            pnpm release:plugins:npm:check
          fi

      - name: Resolve plugin release plan
        id: plan
        env:
          PUBLISH_SCOPE: ${{ github.event_name == 'workflow_dispatch' && inputs.publish_scope || '' }}
          RELEASE_PLUGINS: ${{ github.event_name == 'workflow_dispatch' && inputs.plugins || '' }}
          BASE_REF: ${{ github.event_name != 'workflow_dispatch' && github.event.before || '' }}
          HEAD_REF: ${{ steps.ref.outputs.sha }}
        run: |
          set -euo pipefail
          mkdir -p .local
          if [[ -n "${PUBLISH_SCOPE}" ]]; then
            plan_args=(--selection-mode "${PUBLISH_SCOPE}")
            if [[ -n "${RELEASE_PLUGINS}" ]]; then
              plan_args+=(--plugins "${RELEASE_PLUGINS}")
            fi
            node --import tsx scripts/plugin-npm-release-plan.ts "${plan_args[@]}" > .local/plugin-npm-release-plan.json
          elif [[ -n "${BASE_REF}" ]]; then
            node --import tsx scripts/plugin-npm-release-plan.ts --base-ref "${BASE_REF}" --head-ref "${HEAD_REF}" > .local/plugin-npm-release-plan.json
          else
            node --import tsx scripts/plugin-npm-release-plan.ts > .local/plugin-npm-release-plan.json
          fi

          cat .local/plugin-npm-release-plan.json

          candidate_count="$(jq -r '.candidates | length' .local/plugin-npm-release-plan.json)"
          has_candidates="false"
          if [[ "${candidate_count}" != "0" ]]; then
            has_candidates="true"
          fi
          matrix_json="$(jq -c '.candidates' .local/plugin-npm-release-plan.json)"

          {
            echo "candidate_count=${candidate_count}"
            echo "has_candidates=${has_candidates}"
            echo "matrix=${matrix_json}"
          } >> "$GITHUB_OUTPUT"

          echo "Plugin release candidates:"
          jq -r '.candidates[]? | "- \(.packageName)@\(.version) [\(.publishTag)] from \(.packageDir)"' .local/plugin-npm-release-plan.json

          echo "Already published / skipped:"
          jq -r '.skippedPublished[]? | "- \(.packageName)@\(.version)"' .local/plugin-npm-release-plan.json

  preview_plugin_pack:
    needs: preview_plugins_npm
    if: needs.preview_plugins_npm.outputs.has_candidates == 'true'
    runs-on: ubuntu-latest
    permissions:
      contents: read
    strategy:
      fail-fast: false
      matrix:
        plugin: ${{ fromJson(needs.preview_plugins_npm.outputs.matrix) }}
    steps:
      - name: Checkout
        uses: actions/checkout@v6
        with:
          ref: ${{ needs.preview_plugins_npm.outputs.ref_sha }}
          fetch-depth: 1

      - name: Setup Node environment
        uses: ./.github/actions/setup-node-env
        with:
          node-version: ${{ env.NODE_VERSION }}
          pnpm-version: ${{ env.PNPM_VERSION }}
          install-bun: "false"
          use-sticky-disk: "false"
          install-deps: "false"

      - name: Preview publish command
        run: bash scripts/plugin-npm-publish.sh --dry-run "${{ matrix.plugin.packageDir }}"

      - name: Preview npm pack contents
        working-directory: ${{ matrix.plugin.packageDir }}
        run: npm pack --dry-run --json --ignore-scripts

  publish_plugins_npm:
    needs: [preview_plugins_npm, preview_plugin_pack]
    if: github.event_name == 'workflow_dispatch' && needs.preview_plugins_npm.outputs.has_candidates == 'true'
    runs-on: ubuntu-latest
    environment: npm-release
    permissions:
      contents: read
      id-token: write
    strategy:
      fail-fast: false
      matrix:
        plugin: ${{ fromJson(needs.preview_plugins_npm.outputs.matrix) }}
    steps:
      - name: Checkout
        uses: actions/checkout@v6
        with:
          ref: ${{ needs.preview_plugins_npm.outputs.ref_sha }}
          fetch-depth: 1

      - name: Setup Node environment
        uses: ./.github/actions/setup-node-env
        with:
          node-version: ${{ env.NODE_VERSION }}
          pnpm-version: ${{ env.PNPM_VERSION }}
          install-bun: "false"
          use-sticky-disk: "false"
          install-deps: "false"

      - name: Ensure version is not already published
        env:
          PACKAGE_NAME: ${{ matrix.plugin.packageName }}
          PACKAGE_VERSION: ${{ matrix.plugin.version }}
        run: |
          set -euo pipefail
          if npm view "${PACKAGE_NAME}@${PACKAGE_VERSION}" version >/dev/null 2>&1; then
            echo "${PACKAGE_NAME}@${PACKAGE_VERSION} is already published on npm."
            exit 1
          fi

      - name: Publish
        run: bash scripts/plugin-npm-publish.sh --publish "${{ matrix.plugin.packageDir }}"
