name: On Release Merge

on:
  pull_request:
    types: [closed]
    branches:
      - main
    paths:
      - 'pyproject.toml'

jobs:
  create-tag-and-release:
    if: github.event.pull_request.merged == true && startsWith(github.event.pull_request.head.ref, 'release/')
    runs-on: ubuntu-latest

    steps:
      - name: Checkout code
        uses: actions/checkout@v3
        with:
          fetch-depth: 0

      - name: Set up Python
        uses: actions/setup-python@v4
        with:
          python-version: '3.12'

      - name: Get version
        id: get_version
        run: |
          VERSION=$(grep '^version = ' pyproject.toml | sed -E "s/version = \"([0-9]+\.[0-9]+\.[0-9]+)\"/\1/")
          echo "version=$VERSION" >> $GITHUB_OUTPUT

      - name: Create tag
        run: |
          VERSION=${{ steps.get_version.outputs.version }}
          TAG_NAME="v$VERSION"
          git config user.name "github-actions"
          git config user.email "github-actions@github.com"
          git tag "$TAG_NAME"
          git push origin "$TAG_NAME"

      - name: Create release
        uses: actions/create-release@v1
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        with:
          tag_name: v${{ steps.get_version.outputs.version }}
          release_name: v${{ steps.get_version.outputs.version }}
          body: |
            This release includes the following changes:
            - Version bump to ${{ steps.get_version.outputs.version }}
          draft: false
          prerelease: false

  publish-to-pypi:
    if: github.event.pull_request.merged == true && startsWith(github.event.pull_request.head.ref, 'release/')
    runs-on: ubuntu-latest
    needs: create-tag-and-release

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

      - name: Set up Python
        uses: actions/setup-python@v4
        with:
          python-version: '3.12'

      - name: Install build dependencies
        run: |
          python -m pip install --upgrade pip
          pip install build twine

      - name: Build package
        run: python -m build

      - name: Check package
        run: twine check dist/*

      - name: Publish to PyPI
        env:
          TWINE_USERNAME: __token__
          TWINE_PASSWORD: ${{ secrets.PYPI_API_TOKEN }}
        run: twine upload dist/* 
