name: Release

on:
  push:
    tags:
      - 'v*.*.*'  # Triggers on tags like v0.1.1, v0.2.0, v1.0.0

permissions:
  contents: write
  id-token: write  # Required for PyPI trusted publishing

jobs:
  build-and-publish:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0  # Required for setuptools-scm to work correctly

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

      - name: Install build dependencies
        run: |
          python -m pip install --upgrade pip
          pip install build twine setuptools wheel setuptools-scm[toml]

      - name: Extract version from tag
        id: version
        run: |
          TAG_NAME=${GITHUB_REF#refs/tags/}
          # Remove 'v' prefix if present for version
          VERSION=${TAG_NAME#v}
          echo "version=$VERSION" >> $GITHUB_OUTPUT
          echo "Building version: $VERSION"

      - name: Update version in pyproject.toml
        run: |
          VERSION="${{ steps.version.outputs.version }}"
          # Update version in pyproject.toml
          sed -i "s/^version = \".*\"/version = \"$VERSION\"/" pyproject.toml
          # Also update setup.py if it has a hardcoded version
          sed -i "s/version = \".*\"/version = \"$VERSION\"/" setup.py 2>/dev/null || true
          echo "Updated version to $VERSION"
          # Verify the update
          grep "version = \"$VERSION\"" pyproject.toml

      - name: Build package
        run: python -m build

      - name: Verify package
        run: |
          python -m twine check dist/*

      - name: Publish to PyPI
        uses: pypa/gh-action-pypi-publish@release/v1
        # Uses PyPI trusted publishing - no API token needed!
        # Make sure to enable trusted publishing in PyPI project settings

      - name: Extract tag name
        id: tag
        run: |
          TAG_NAME=${GITHUB_REF#refs/tags/}
          echo "tag_name=$TAG_NAME" >> $GITHUB_OUTPUT
          # Remove 'v' prefix if present for release name
          RELEASE_NAME=${TAG_NAME#v}
          echo "release_name=$RELEASE_NAME" >> $GITHUB_OUTPUT

      - name: Create GitHub Release
        uses: softprops/action-gh-release@v1
        with:
          name: Release ${{ steps.tag.outputs.release_name }}
          body: |
            ## Release ${{ steps.tag.outputs.release_name }}

            This release was automatically created from tag `${{ steps.tag.outputs.tag_name }}`.

            ### Installation

            ```bash
            pip install baselinr==${{ steps.tag.outputs.release_name }}
            ```

            ### What's Changed

            See the [full changelog](https://github.com/${{ github.repository }}/compare/${{ steps.tag.outputs.tag_name }}^...${{ steps.tag.outputs.tag_name }}) for details.

          draft: false
          prerelease: false
