name: Release

on:
  push:
    tags:
      - "v*"

permissions:
  contents: write

jobs:
  build-and-release:
    name: Build ${{ matrix.target }}
    runs-on: ${{ matrix.os }}
    strategy:
      fail-fast: false
      matrix:
        include:
          # Linux
          - os: ubuntu-latest
            target: x86_64-unknown-linux-gnu
            name: cx-linux

          # Windows
          - os: windows-latest
            target: x86_64-pc-windows-msvc
            name: cx-windows.exe

          # macOS (Apple Silicon - M1/M2)
          - os: macos-latest
            target: aarch64-apple-darwin
            name: cx-macos-arm64

          # macOS (Intel)
          - os: macos-15
            target: x86_64-apple-darwin
            name: cx-macos-intel

    steps:
      - uses: actions/checkout@v6

      - name: Install Perl (Windows only)
        if: matrix.os == 'windows-latest'
        uses: shogo82148/actions-setup-perl@v1

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

      - name: Cache Cargo Registry & Target
        uses: actions/cache@v4
        with:
          path: |
            ~/.cargo/registry
            ~/.cargo/git
            target
          key: ${{ runner.os }}-${{ matrix.target }}-cargo-${{ hashFiles('**/Cargo.toml') }}
          restore-keys: |
            ${{ runner.os }}-${{ matrix.target }}-cargo-

      - name: Build Binary
        run: cargo build --release --target ${{ matrix.target }} --locked

      - name: Prepare Artifact (Unix)
        if: matrix.os != 'windows-latest'
        run: |
          mv target/${{ matrix.target }}/release/cx target/${{ matrix.target }}/release/${{ matrix.name }}

      - name: Prepare Artifact (Windows)
        if: matrix.os == 'windows-latest'
        run: |
          Move-Item -Force target/${{ matrix.target }}/release/cx.exe target/${{ matrix.target }}/release/${{ matrix.name }}

      - name: Upload Artifact
        uses: actions/upload-artifact@v5
        with:
          name: ${{ matrix.name }}
          path: target/${{ matrix.target }}/release/${{ matrix.name }}

  publish:
    needs: build-and-release
    runs-on: ubuntu-latest
    steps:
      - uses: actions/download-artifact@v6
        with:
          path: artifacts

      - name: Create Release
        uses: softprops/action-gh-release@v2
        with:
          files: |
            artifacts/cx-linux/cx-linux
            artifacts/cx-windows.exe/cx-windows.exe
            artifacts/cx-macos-arm64/cx-macos-arm64
            artifacts/cx-macos-intel/cx-macos-intel
          generate_release_notes: true
          draft: true
