name: Publish

on:
  release:
    types: [published]

permissions:
  contents: read
  id-token: write

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

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

      - 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-packages
          path: dist/
          retention-days: 7

  publish-pypi:
    needs: build
    runs-on: ubuntu-latest
    permissions:
      id-token: write
    environment:
      name: pypi
      url: https://pypi.org/project/venomqa
    steps:
      - name: Download build artifacts
        uses: actions/download-artifact@v4
        with:
          name: dist-packages
          path: dist/

      - name: Publish to PyPI
        uses: pypa/gh-action-pypi-publish@release/v1

  update-release-notes:
    needs: publish-pypi
    runs-on: ubuntu-latest
    permissions:
      contents: write
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Generate release notes
        id: notes
        run: |
          VERSION=${{ github.event.release.tag_name }}
          cat << EOF > release_notes.md
          ## What's Changed in ${VERSION}

          ### Installation

          \`\`\`bash
          pip install venomqa==${VERSION#v}
          \`\`\`

          ### Changelog

          See [CHANGELOG.md](https://github.com/${{ github.repository }}/blob/main/CHANGELOG.md) for detailed changes.

          **Full Changelog**: https://github.com/${{ github.repository }}/compare/${{ github.event.release.prerelease == true && 'previous-tag' || 'previous-tag' }}...${VERSION}
          EOF
          echo "release_notes_file=release_notes.md" >> $GITHUB_OUTPUT

      - name: Update release
        uses: softprops/action-gh-release@v2
        with:
          body_path: release_notes.md
          append_body: true
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
