name: Release

on:
  push:
    tags:
      - 'v*'

env:
  CARGO_TERM_COLOR: always

permissions:
  contents: write

jobs:
  build:
    name: Build ${{ matrix.target }}
    runs-on: ${{ matrix.os }}
    strategy:
      fail-fast: true
      matrix:
        include:
          - target: aarch64-apple-darwin
            os: macos-15
            use-cross: false
          - target: x86_64-apple-darwin
            os: macos-15-intel
            use-cross: false
          - target: x86_64-unknown-linux-gnu
            os: ubuntu-latest
            use-cross: false
          - target: aarch64-unknown-linux-gnu
            os: ubuntu-latest
            use-cross: true

    steps:
      - name: Checkout code
        uses: actions/checkout@v6

      - name: Install Rust toolchain
        uses: dtolnay/rust-toolchain@stable
        with:
          targets: ${{ matrix.target }}

      - name: Install cross
        if: matrix.use-cross
        run: cargo install cross --git https://github.com/cross-rs/cross --tag v0.2.5

      - name: Build release binary
        run: |
          if [ "${{ matrix.use-cross }}" = "true" ]; then
            cross build --release --target ${{ matrix.target }}
          else
            cargo build --release --target ${{ matrix.target }}
          fi

      - name: Code sign macOS binary
        if: runner.os == 'macOS'
        run: codesign --force -s - target/${{ matrix.target }}/release/pr-bro

      - name: Create archive directory
        run: mkdir -p dist

      - name: Package release archive
        run: |
          mkdir -p staging
          cp target/${{ matrix.target }}/release/pr-bro staging/
          cp LICENSE README.md staging/
          cd staging && tar -czf ../dist/pr-bro-${{ github.ref_name }}-${{ matrix.target }}.tar.gz *

      - name: Generate checksum
        run: |
          cd dist
          if [ "$RUNNER_OS" = "macOS" ]; then
            shasum -a 256 pr-bro-${{ github.ref_name }}-${{ matrix.target }}.tar.gz > pr-bro-${{ github.ref_name }}-${{ matrix.target }}.tar.gz.sha256
          else
            sha256sum pr-bro-${{ github.ref_name }}-${{ matrix.target }}.tar.gz > pr-bro-${{ github.ref_name }}-${{ matrix.target }}.tar.gz.sha256
          fi

      - name: Upload release artifacts
        uses: actions/upload-artifact@v6
        with:
          name: release-${{ matrix.target }}
          path: dist/*

  release:
    name: Create GitHub Release
    needs: build
    runs-on: ubuntu-latest

    steps:
      - name: Checkout code
        uses: actions/checkout@v6

      - name: Download all artifacts
        uses: actions/download-artifact@v7
        with:
          path: dist
          merge-multiple: true

      - name: Generate combined SHA256SUMS
        run: |
          cd dist
          cat *.sha256 | sort > SHA256SUMS

      - name: Create GitHub Release
        uses: softprops/action-gh-release@v2
        with:
          generate_release_notes: true
          prerelease: ${{ contains(github.ref_name, '-rc') || contains(github.ref_name, '-beta') || contains(github.ref_name, '-alpha') }}
          files: dist/*
          fail_on_unmatched_files: true

      - name: Update Homebrew tap
        id: update-tap
        continue-on-error: true
        env:
          HOMEBREW_TAP_TOKEN: ${{ secrets.HOMEBREW_TAP_TOKEN }}
        run: |
          # Extract version without 'v' prefix
          VERSION="${GITHUB_REF_NAME#v}"
          TAG="${GITHUB_REF_NAME}"

          # Calculate SHA256 for macOS archives from downloaded artifacts
          INTEL_SHA256=$(sha256sum dist/pr-bro-${TAG}-x86_64-apple-darwin.tar.gz | cut -d ' ' -f1)
          ARM_SHA256=$(sha256sum dist/pr-bro-${TAG}-aarch64-apple-darwin.tar.gz | cut -d ' ' -f1)

          echo "Version: ${VERSION}"
          echo "Intel SHA256: ${INTEL_SHA256}"
          echo "ARM SHA256: ${ARM_SHA256}"

          # Clone tap repo
          git clone "https://x-access-token:${HOMEBREW_TAP_TOKEN}@github.com/toniperic/homebrew-tap.git" tap-repo

          # Generate formula from template
          sed -e "s/HOMEBREW_VERSION/${VERSION}/g" \
              -e "s/INTEL_SHA256/${INTEL_SHA256}/g" \
              -e "s/ARM_SHA256/${ARM_SHA256}/g" \
              homebrew/pr-bro.rb.template > tap-repo/Formula/pr-bro.rb

          # Commit and push
          cd tap-repo
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          git add Formula/pr-bro.rb
          git diff --cached --quiet && echo "No changes to formula" && exit 0
          git commit -m "pr-bro ${TAG}"
          git push

      - name: Create issue if tap update failed
        if: steps.update-tap.outcome == 'failure'
        uses: actions/github-script@v8
        with:
          github-token: ${{ secrets.HOMEBREW_TAP_TOKEN }}
          script: |
            const tag = context.ref.replace('refs/tags/', '');
            await github.rest.issues.create({
              owner: 'toniperic',
              repo: 'homebrew-tap',
              title: `Formula update failed for ${tag}`,
              body: [
                `## Formula Update Failure`,
                ``,
                `The automated Homebrew formula update failed for release **${tag}**.`,
                ``,
                `**Release:** https://github.com/${context.repo.owner}/${context.repo.repo}/releases/tag/${tag}`,
                `**Workflow run:** https://github.com/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`,
                ``,
                `### Manual Update Steps`,
                `1. Download the macOS release archives`,
                `2. Calculate SHA256: \`shasum -a 256 pr-bro-${tag}-*.tar.gz\``,
                `3. Update \`Formula/pr-bro.rb\` with new version and checksums`,
                `4. Push to main branch`,
              ].join('\n')
            });
