name: Release

on:
  push:
    tags:
      - "v*"

permissions:
  contents: write
  packages: write

jobs:
  test:
    name: Test
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Set up Rust
        uses: dtolnay/rust-toolchain@stable
        with:
          components: rustfmt, clippy

      - name: Cache dependencies
        uses: Swatinem/rust-cache@v2

      - name: Check formatting
        run: cargo fmt --all -- --check

      - name: Run clippy
        run: cargo clippy -- -D warnings -A deprecated

      - name: Run tests
        run: cargo test --all-features

  build:
    name: Build and release
    runs-on: ubuntu-latest
    needs: test
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Set up Rust
        uses: dtolnay/rust-toolchain@stable

      - name: Cache dependencies
        uses: Swatinem/rust-cache@v2

      - name: Install git-cliff
        run: cargo install git-cliff

      - name: Install Nushell
        run: cargo install nu --locked

      - name: Prepare release
        run: nu scripts/release_prepare.nu ${{ github.ref_name }}

      - name: Build release
        run: cargo build --release --all-features

      - name: Create GitHub Release
        uses: softprops/action-gh-release@v1
        with:
          body_path: RELEASE_CHANGELOG.md
          files: |
            LICENSE
            README.md
            CHANGELOG.md
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Publish to crates.io
        if: env.CRATES_IO_TOKEN != ''
        env:
          CRATES_IO_TOKEN: ${{ secrets.CRATES_IO_TOKEN }}
        run: |
          echo "Publishing to crates.io..."
          cargo publish --token $CRATES_IO_TOKEN --allow-dirty

      - name: Skip crates.io publish
        if: env.CRATES_IO_TOKEN == ''
        env:
          CRATES_IO_TOKEN: ${{ secrets.CRATES_IO_TOKEN }}
        run: |
          echo "CRATES_IO_TOKEN not set — skipping crates.io publication."
          echo "Add CRATES_IO_TOKEN to your GitHub repository secrets to enable auto-publish."
