name: Update Changelog

on:
  release:
    types: [published]

permissions:
  contents: write

jobs:
  update-changelog:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
          ref: ${{ github.event.release.target_commitish }}

      - name: Setup Python
        uses: actions/setup-python@v6
        with:
          python-version: '3.x'

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

      - name: Generate changelog
        run: git-cliff --output CHANGELOG.md --tag ${{ github.event.release.tag_name }}

      - name: Commit and push changes
        run: |
          git config --local user.email "github-actions[bot]@users.noreply.github.com"
          git config --local user.name "github-actions[bot]"
          git add CHANGELOG.md
          git diff --quiet && git diff --staged --quiet || git commit -m "docs: update CHANGELOG.md for ${{ github.event.release.tag_name }} [skip ci]"
          git push origin HEAD:${{ github.event.release.target_commitish }}
