name: Release

on:
  push:
    tags:
      - "*.*.*"

permissions:
  contents: write

jobs:
  release:
    name: Build and release
    runs-on: ubuntu-latest

    steps:
      - name: Checkout
        uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
        with:
          fetch-depth: 0
          persist-credentials: false

      - name: Setup Node.js
        uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6
        with:
          node-version: 26
          package-manager-cache: false

      - name: Install dependencies
        run: npm ci --ignore-scripts

      - name: Install recorded Codex CLI
        run: npm install --global "@openai/codex@$(node scripts/app-server-compatibility.mjs --tested-cli-version)"

      - name: Check API baselines
        run: npm run api:baseline

      - name: Check generated app-server bindings
        run: npm run generate:app-server-types:check

      - name: Check release version
        run: npm run release:check
        env:
          RELEASE_VERSION: ${{ github.ref_name }}

      - name: Check release commit messages
        env:
          TAG: ${{ github.ref_name }}
        run: |
          PREVIOUS_TAG="$(node -p 'Object.keys(require("./versions.json")).at(-2)')"
          git rev-parse --verify "refs/tags/$PREVIOUS_TAG"
          npm run commitlint -- --from "$PREVIOUS_TAG" --to "$TAG" --verbose

      - name: Run checks and build
        run: npm run check

      - name: Create GitHub release
        env:
          GH_TOKEN: ${{ github.token }}
          TAG: ${{ github.ref_name }}
        run: |
          NOTES_FILE=".github/release-notes/$TAG.md"
          if [ ! -f "$NOTES_FILE" ]; then
            echo "Release notes file is required at $NOTES_FILE"
            exit 1
          fi

          if gh release view "$TAG" >/dev/null 2>&1; then
            gh release edit "$TAG" \
              --title "$TAG" \
              --notes-file "$NOTES_FILE" \
              --verify-tag
          else
            gh release create "$TAG" \
              main.js manifest.json styles.css \
              --title "$TAG" \
              --notes-file "$NOTES_FILE" \
              --verify-tag
          fi
