name: Build Binaries

on:
  push:
    tags:
      - 'v*'
  workflow_dispatch:
    inputs:
      tag:
        description: 'Tag to build (e.g., v0.12.0)'
        required: true
        type: string

permissions:
  contents: write

jobs:
  build:
    runs-on: ubuntu-latest
    env:
      RELEASE_TAG: ${{ github.event.inputs.tag || github.ref_name }}
    steps:
      - name: Checkout
        uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
        with:
          ref: ${{ env.RELEASE_TAG }}

      - name: Setup Bun
        uses: oven-sh/setup-bun@4bc047ad259df6fc24a6c9b0f9a0cb08cf17fbe5 # v2.0.1
        with:
          bun-version: 1.2.20

      - name: Setup Node.js
        uses: actions/setup-node@39370e3970a6d050c480ffad4ff0ed4d3fdee5af # v4.1.0
        with:
          node-version: '22'
          registry-url: 'https://registry.npmjs.org'

      - name: Build binaries
        run: ./scripts/build-binaries.sh

      - name: Extract changelog for this version
        id: changelog
        run: |
          VERSION="${RELEASE_TAG}"
          VERSION="${VERSION#v}"  # Remove 'v' prefix
          
          # Extract changelog section for this version
          cd packages/coding-agent
          awk "/^## \[${VERSION}\]/{flag=1; next} /^## \[/{flag=0} flag" CHANGELOG.md > /tmp/release-notes.md
          
          # If empty, use a default message
          if [ ! -s /tmp/release-notes.md ]; then
            echo "Release ${VERSION}" > /tmp/release-notes.md
          fi

      - name: Create GitHub Release and upload binaries
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          cd packages/coding-agent/binaries
          
          # Create release with changelog notes (or update if exists)
          gh release create "${RELEASE_TAG}" \
            --title "${RELEASE_TAG}" \
            --notes-file /tmp/release-notes.md \
            pi-darwin-arm64.tar.gz \
            pi-darwin-x64.tar.gz \
            pi-linux-x64.tar.gz \
            pi-linux-arm64.tar.gz \
            pi-windows-x64.zip \
            2>/dev/null || \
          gh release upload "${RELEASE_TAG}" \
            pi-darwin-arm64.tar.gz \
            pi-darwin-x64.tar.gz \
            pi-linux-x64.tar.gz \
            pi-linux-arm64.tar.gz \
            pi-windows-x64.zip \
            --clobber
