name: Release

on:
  push:
    tags:
      - 'v*'
  release:
    types: [published]

permissions:
  contents: read

jobs:
  build:
    runs-on: ubuntu-latest
    permissions:
      contents: read
    
    steps:
    - uses: actions/checkout@v4
    
    - name: Set up Python
      uses: actions/setup-python@v5
      with:
        python-version: '3.11'
    
    - 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: Upload build artifacts
      uses: actions/upload-artifact@v4
      with:
        name: dist
        path: dist/

  pypi-publish:
    needs: build
    name: upload release to PyPI
    if: github.event_name == 'release' && github.event.action == 'published'
    runs-on: ubuntu-latest
    permissions:
      id-token: write
    steps:
      - name: Download build artifacts
        uses: actions/download-artifact@v4
        with:
          name: dist
          path: dist/
      - name: Publish package distributions to PyPI
        uses: pypa/gh-action-pypi-publish@release/v1

  publish-github:
    needs: build
    runs-on: ubuntu-latest
    permissions:
      contents: write
    if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')
    
    steps:
    - uses: actions/checkout@v4
    
    - name: Download build artifacts
      uses: actions/download-artifact@v4
      with:
        name: dist
        path: dist/
    
    - name: Extract tag name
      id: tag
      run: echo "tag=${GITHUB_REF#refs/tags/}" >> $GITHUB_OUTPUT
    
    - name: Extract changelog
      id: changelog
      run: |
        # Extract changelog section for this version
        VERSION=$(echo ${{ steps.tag.outputs.tag }} | sed 's/^v//')
        awk "/^## \[$VERSION\]/{flag=1; next} /^## \[/{flag=0} flag" CHANGELOG.md > release_notes.md
    
    - name: Create GitHub Release
      uses: softprops/action-gh-release@v2
      with:
        tag_name: ${{ steps.tag.outputs.tag }}
        name: Release ${{ steps.tag.outputs.tag }}
        body_path: release_notes.md
        files: |
          dist/*.whl
          dist/*.tar.gz
        draft: false
        prerelease: false
      env:
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
