name: Release Please

on:
  push:
    branches:
      - main

env:
  PROTOC_VERSION: '3.25.3'

permissions:
  contents: write
  pull-requests: write

jobs:
  release-please:
    runs-on: ubuntu-latest
    steps:
      - uses: googleapis/release-please-action@v4
        id: release

      # Publish to crates.io when a release is created
      - name: Checkout code
        if: ${{ steps.release.outputs.release_created }}
        uses: actions/checkout@v4

      - name: Install Rust toolchain
        if: ${{ steps.release.outputs.release_created }}
        uses: dtolnay/rust-toolchain@stable

      - name: install protoc
        if: ${{ steps.release.outputs.release_created }}
        uses: taiki-e/install-action@v2
        with:
          tool: protoc@${{ env.PROTOC_VERSION }}

      - name: Cache cargo registry
        if: ${{ steps.release.outputs.release_created }}
        uses: actions/cache@v3
        with:
          path: |
            ~/.cargo/registry
            ~/.cargo/git
            target
          key: ${{ runner.os }}-cargo-release-${{ hashFiles('**/Cargo.lock') }}
          restore-keys: |
            ${{ runner.os }}-cargo-release-

      - name: Publish to crates.io
        if: ${{ steps.release.outputs.release_created }}
        run: cargo publish --token ${{ secrets.CARGO_REGISTRY_TOKEN }}
        env:
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}

      # Optional: Create GitHub release with artifacts
      - name: Build release artifacts
        if: ${{ steps.release.outputs.release_created }}
        run: |
          cargo build --release
          cargo doc --no-deps

      - name: Upload Release Assets
        if: ${{ steps.release.outputs.release_created }}
        uses: softprops/action-gh-release@v1
        with:
          tag_name: ${{ steps.release.outputs.tag_name }}
          files: |
            target/release/libesphome_client.rlib
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
