name: Seed Marketplace Plugins

on:
  workflow_dispatch:
  push:
    branches: [main]
    paths:
      - "packages/plugins/**"
      - ".github/workflows/deploy-marketplace.yml"

permissions:
  contents: read

concurrency:
  group: seed-marketplace
  cancel-in-progress: false

jobs:
  seed:
    name: Seed Plugins
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
        with:
          persist-credentials: false
      - uses: pnpm/action-setup@fc06bc1257f339d1d5d8b3a19a8cae5388b55320 # v4.4.0
      - uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0
        with:
          node-version: 22
          cache: pnpm
      - run: pnpm install --frozen-lockfile

      # Build core (produces the CLI at dist/cli/index.mjs)
      - run: pnpm run --filter emdash... build

      # Bundle and publish each standard-format plugin.
      # Only plugins with a sandbox entry can be marketplace-installed.
      # Invokes the built CLI directly via node since pnpm exec can't
      # resolve binaries from workspace packages (only from dependencies).
      - name: Seed plugins
        run: |
          CLI="node packages/core/dist/cli/index.mjs"
          failures=0
          for dir in packages/plugins/*/; do
            [ -f "$dir/package.json" ] || continue

            # Only include plugins that have a sandbox entry
            if [ ! -f "$dir/src/sandbox-entry.ts" ] && \
               ! grep -q '"./sandbox"' "$dir/package.json" 2>/dev/null; then
              continue
            fi

            name=$(basename "$dir")

            # Skip test-only plugins
            case "$name" in
              marketplace-test|sandboxed-test|api-test) continue ;;
            esac

            echo "::group::$name"
            $CLI plugin publish --build --dir "$dir" --no-wait --registry "$MARKETPLACE_URL" || {
              echo "::warning::Failed to publish $name"
              failures=$((failures + 1))
            }
            echo "::endgroup::"
          done
          if [ "$failures" -gt 0 ]; then
            echo "::error::$failures plugin(s) failed to publish"
            exit 1
          fi
        env:
          EMDASH_MARKETPLACE_TOKEN: ${{ secrets.MARKETPLACE_SEED_TOKEN }}
          MARKETPLACE_URL: https://marketplace.emdashcms.com
