name: Release

on:
  push:
    tags:
      - 'v*'

permissions:
  contents: write
  id-token: write  # Required for OIDC token exchange

jobs:
  build-and-release:
    name: Build and Release
    runs-on: ${{ matrix.os }}
    strategy:
      matrix:
        include:
          - os: ubuntu-latest
            target: x86_64-unknown-linux-gnu
            binary_name: ccstat
            asset_name: ccstat-linux-x86_64
          - os: windows-latest
            target: x86_64-pc-windows-msvc
            binary_name: ccstat.exe
            asset_name: ccstat-windows-x86_64.exe
          - os: macos-latest
            target: x86_64-apple-darwin
            binary_name: ccstat
            asset_name: ccstat-macos-x86_64
          - os: macos-latest
            target: aarch64-apple-darwin
            binary_name: ccstat
            asset_name: ccstat-macos-aarch64

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

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

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

    - name: Compress binary (Unix)
      if: matrix.os != 'windows-latest'
      run: |
        cd target/${{ matrix.target }}/release
        tar czf ${{ matrix.asset_name }}.tar.gz ${{ matrix.binary_name }}
        mv ${{ matrix.asset_name }}.tar.gz ../../../

    - name: Compress binary (Windows)
      if: matrix.os == 'windows-latest'
      run: |
        cd target/${{ matrix.target }}/release
        7z a -tzip ${{ matrix.asset_name }}.zip ${{ matrix.binary_name }}
        mv ${{ matrix.asset_name }}.zip ../../../

    - name: Upload Release Assets
      uses: softprops/action-gh-release@v2
      if: startsWith(github.ref, 'refs/tags/')
      with:
        draft: false
        files: |
          ${{ matrix.asset_name }}.tar.gz
          ${{ matrix.asset_name }}.zip
        fail_on_unmatched_files: false

  publish-crate:
    name: Publish to crates.io
    runs-on: ubuntu-latest
    needs: build-and-release  # Only publish after successful builds
    environment: release  # Optional: for enhanced security
    steps:
    - name: Checkout code
      uses: actions/checkout@v4

    - name: Install Rust
      uses: dtolnay/rust-toolchain@stable

    - name: Authenticate with crates.io
      uses: rust-lang/crates-io-auth-action@v1
      id: auth

    - name: Publish to crates.io
      run: cargo publish
      env:
        CARGO_REGISTRY_TOKEN: ${{ steps.auth.outputs.token }}
