name: Push to Main CI

on:
  push:
    branches:
      - main

permissions:
  contents: write
  packages: write

jobs:
  build-and-package:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Setup pnpm
        uses: pnpm/action-setup@v4
        with:
          version: latest

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 24
          cache: pnpm
          cache-dependency-path: "**/pnpm-lock.yaml"

      - name: Prewarm & Install (workspace)
        run: |
          set -euo pipefail
          pnpm fetch
          pnpm install --frozen-lockfile --offline

      - name: Build All Packages (with exclusions)
        shell: bash
        run: |
          set -euo pipefail

          # List packages to exclude (full paths under repo root)
          EXCLUDED_DIRS=("packages/protobufs" "packages/transport-deno" "packages/ui" "pacakges/web")

          is_excluded() {
            local dir="$1"
            for ex in "${EXCLUDED_DIRS[@]}"; do
              if [[ "$dir" == "$ex" ]]; then
                return 0
              fi
            done
            return 1
          }

          for pkg_dir in packages/*/; do
            pkg_dir="${pkg_dir%/}"  # trim trailing slash

            # Must be a directory with a package.json
            if [[ ! -f "$pkg_dir/package.json" ]]; then
              echo "⚠️  Skipping $pkg_dir (no package.json)"
              continue
            fi

            # Allow for exclusions
            if is_excluded "$pkg_dir"; then
              echo "🚫 Skipping $pkg_dir (excluded)"
              continue
            fi

            # Optionally skip Deno-first packages automatically
            if [[ -f "$pkg_dir/deno.json" || -f "$pkg_dir/deno.jsonc" ]]; then
              echo "🦕 Skipping $pkg_dir (deno project)"
              continue
            fi

            echo "🔧 Building: $pkg_dir"
            # No per-package install needed; workspace install already done
            pnpm -C "$pkg_dir" run build:npm
          done
