name: Build and publish python package

on:
  push:
    tags:
      - "v[0-9]+.[0-9]+"
      - "v[0-9]+.[0-9]+.[0-9]+"

jobs:
  publish-on-pypi:
    runs-on: ubuntu-latest
    permissions:
      contents: write
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          ref: ${{ github.ref }}
          fetch-depth: 0

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

      - name: Install uv
        uses: astral-sh/setup-uv@v3

      - name: Extract version from tag
        id: version
        run: echo "version=${GITHUB_REF_NAME#v}" >> "$GITHUB_OUTPUT"

      - name: Install and test
        run: |
          uv sync --group dev
          uv run pytest

      - name: Clean working tree
        run: git reset --hard ${{ github.ref }}

      - name: Update CHANGELOG for release
        env:
          VERSION: ${{ steps.version.outputs.version }}
          TAG: ${{ github.ref_name }}
        run: |
          DATE=$(date +%Y-%m-%d)
          sed -i "s/^## \[Unreleased\].*/## [Unreleased]\n\n## [${VERSION}] — ${DATE}/" CHANGELOG.md
          sed -i "s|\[Unreleased\]: \(.*\)/compare/.*\.\.\.HEAD|[Unreleased]: \1/compare/${TAG}...HEAD|" CHANGELOG.md
          PREV_TAG=$(git describe --tags --abbrev=0 "${TAG}^" 2>/dev/null || echo "")
          if [ -n "$PREV_TAG" ]; then
            REPO_URL="https://github.com/hugochinchilla/pysyringe"
            sed -i "/^\[Unreleased\]:/a [${VERSION}]: ${REPO_URL}/compare/${PREV_TAG}...${TAG}" CHANGELOG.md
          fi

      - name: Build wheel and sdist
        env:
          SETUPTOOLS_SCM_PRETEND_VERSION: ${{ steps.version.outputs.version }}
        run: uv build

      - name: Create GitHub Release
        uses: softprops/action-gh-release@v2
        with:
          files: dist/*
          generate_release_notes: true
          draft: false
          prerelease: false

      - name: Publish to PyPI
        uses: pypa/gh-action-pypi-publish@v1.12.4
        with:
          password: ${{ secrets.PYPI_API_TOKEN }}

      - name: Update master with release artifacts
        env:
          VERSION: ${{ steps.version.outputs.version }}
          TAG: ${{ github.ref_name }}
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          git checkout master
          git checkout "${TAG}" -- CHANGELOG.md
          echo "__version__ = \"${VERSION}\"" > pysyringe/__init__.py
          uv sync --group dev
          uv run python docs/build.py
          git checkout -- pysyringe/__init__.py
          git add CHANGELOG.md docs/index.html
          git commit -m "update CHANGELOG and docs for ${TAG} release"
          git push origin master
