name: Release

on:
  push:
    tags: ["broomva-cli-v*"]

permissions:
  contents: write

env:
  CARGO_TERM_COLOR: always

defaults:
  run:
    working-directory: crates/broomva-cli

jobs:
  test:
    name: Test
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: dtolnay/rust-toolchain@stable
        with:
          toolchain: "1.88"
          components: clippy, rustfmt
      - uses: Swatinem/rust-cache@v2
        with:
          workspaces: crates/broomva-cli
      - run: cargo check
      - run: cargo clippy -- -D warnings
      - run: cargo fmt --all -- --check
      - run: cargo test

  build:
    name: Build (${{ matrix.target }})
    needs: test
    runs-on: ${{ matrix.os }}
    strategy:
      matrix:
        include:
          - os: ubuntu-latest
            target: x86_64-unknown-linux-gnu
            artifact: broomva-linux-amd64
          - os: macos-latest
            target: x86_64-apple-darwin
            artifact: broomva-macos-amd64
          - os: macos-latest
            target: aarch64-apple-darwin
            artifact: broomva-macos-arm64
    steps:
      - uses: actions/checkout@v4
      - uses: dtolnay/rust-toolchain@stable
        with:
          toolchain: "1.88"
          targets: ${{ matrix.target }}
      - uses: Swatinem/rust-cache@v2
        with:
          workspaces: crates/broomva-cli
      - run: cargo build --release --target ${{ matrix.target }}
      - run: |
          mkdir -p dist
          cp target/${{ matrix.target }}/release/broomva dist/${{ matrix.artifact }}
          chmod +x dist/${{ matrix.artifact }}
      - uses: actions/upload-artifact@v4
        with:
          name: ${{ matrix.artifact }}
          path: crates/broomva-cli/dist/${{ matrix.artifact }}

  release:
    name: GitHub Release
    needs: build
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/download-artifact@v4
        with:
          path: artifacts
      - name: Create release
        env:
          GH_TOKEN: ${{ github.token }}
        run: |
          TAG="${GITHUB_REF_NAME}"
          VERSION="${TAG#broomva-cli-v}"
          mkdir -p release
          for dir in artifacts/*/; do
            cp "$dir"* release/ 2>/dev/null || true
          done
          gh release create "$TAG" \
            --title "broomva-cli v${VERSION}" \
            --generate-notes \
            release/*

  publish:
    name: Publish to crates.io
    needs: test
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: dtolnay/rust-toolchain@stable
        with:
          toolchain: "1.88"
      - uses: Swatinem/rust-cache@v2
        with:
          workspaces: crates/broomva-cli
      - name: Publish
        env:
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
        run: cargo publish --no-verify || echo "Already published or token not configured"
