name: Release

on:
  push:
    tags:
      - 'v*'

permissions: {}

jobs:
  verify:
    runs-on: ubuntu-latest
    environment: release # Optional: for enhanced security
    permissions:
      contents: read
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-node@v7
        with:
          node-version: '24'
      - name: Configure sandboxing
        run: |
          sudo apt-get update
          sudo apt-get install --yes bubblewrap
          sudo sysctl -w kernel.unprivileged_userns_clone=1
          if [ -f /proc/sys/kernel/apparmor_restrict_unprivileged_userns ]; then
            sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0
          fi
      - run: npm ci
      - run: npm run typecheck
      - run: npm test
      - name: Run e2e tests
        env:
          OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
        run: npm run test:e2e

  publish-to-npm:
    needs: verify
    runs-on: ubuntu-latest
    environment: release # Optional: for enhanced security
    permissions:
      contents: read
      id-token: write
    steps:
      - uses: actions/checkout@v7
      - uses: actions/setup-node@v7
        with:
          node-version: '24'
          registry-url: 'https://registry.npmjs.org'
      - run: npm ci
      - run: npm publish --access public

  create-release:
    needs: publish-to-npm
    runs-on: ubuntu-latest
    environment: release
    permissions: {}
    steps:
      - name: Generate GitHub token
        uses: actions/create-github-app-token@v3
        id: generate-token
        with:
          app-id: ${{ secrets.RELEASE_PLZ_APP_ID }}
          private-key: ${{ secrets.RELEASE_PLZ_APP_PRIVATE_KEY }}

      - name: Create Release
        uses: softprops/action-gh-release@3d0d9888cb7fd7b750713d6e236d1fcb99157228 # v3.0.2
        with:
          token: ${{ steps.generate-token.outputs.token }}
          generate_release_notes: true

  trigger-registry-update:
    needs: create-release
    runs-on: ubuntu-latest
    environment: release
    permissions: {}
    steps:
      - name: Generate token scoped to the registry repo
        uses: actions/create-github-app-token@v3
        id: registry-token
        with:
          app-id: ${{ secrets.REGISTRY_UPDATER_APP_ID }}
          private-key: ${{ secrets.REGISTRY_UPDATER_APP_PRIVATE_KEY }}
          owner: ${{ github.repository_owner }}
          repositories: registry

      - name: Dispatch registry version update
        env:
          GH_TOKEN: ${{ steps.registry-token.outputs.token }}
        run: |
          gh workflow run update-versions.yml \
            --repo ${{ github.repository_owner }}/registry \
            --ref main \
            -f apply=true \
            -f agents=codex-acp
