name: Create Release and Publish to PyPI
# Creates a GitHub release when a PR is merged to main (using PR title as version and body as release notes), then publishes to PyPI.

on:
  pull_request:
    types: [closed]
    branches:
      - main

jobs:
  create-release-and-publish:
    if: github.event.pull_request.merged == true
    runs-on: ubuntu-latest
    environment:
      name: PyPI
      url: https://pypi.org/p/scrapling
    permissions:
      contents: write
      id-token: write
    steps:
      - uses: actions/checkout@v6
        with:
          fetch-depth: 0

      - name: Get PR title
        id: pr_title
        run: echo "title=${{ github.event.pull_request.title }}" >> $GITHUB_OUTPUT

      - name: Save PR body to file
        uses: actions/github-script@v8
        with:
          script: |
            const fs = require('fs');
            fs.writeFileSync('pr_body.md', context.payload.pull_request.body || '');

      - name: Extract version
        id: extract_version
        run: |
          PR_TITLE="${{ steps.pr_title.outputs.title }}"
          if [[ $PR_TITLE =~ ^v ]]; then
            echo "version=$PR_TITLE" >> $GITHUB_OUTPUT
            echo "Valid version format found in PR title: $PR_TITLE"
          else
            echo "Error: PR title '$PR_TITLE' must start with 'v' (e.g., 'v1.0.0') to create a release."
            exit 1
          fi

      - name: Create Release
        uses: softprops/action-gh-release@v2
        with:
          tag_name: ${{ steps.extract_version.outputs.version }}
          name: Release ${{ steps.extract_version.outputs.version }}
          body_path: pr_body.md
          draft: false
          prerelease: false
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

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

      - name: Upgrade pip
        run: python3 -m pip install --upgrade pip

      - name: Install build
        run: python3 -m pip install --upgrade build twine setuptools

      - name: Build a binary wheel and a source tarball
        run: python3 -m build --sdist --wheel --outdir dist/

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