name: "Release on PyPi and GitHub"

on:
  push:
    tags:
      - "v*"

jobs:
  release:
    name: "Release pushed tag"
    runs-on: "ubuntu-latest"
    permissions:
      id-token: write
      contents: write
    steps:
      - name: "Checkout the repository"
        uses: "actions/checkout@v4.2.2"

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

      - name: "Install requirements"
        run: python3 -m pip install -r requirements.txt

      - name: "Lint with Ruff"
        run: python3 -m ruff check .

      - name: "Check format with Ruff"
        run: python3 -m ruff format . --check

      - name: "Install package"
        run: |
          python -m pip install -e .

      - name: "Test package"
        run: |
          python -m pytest --cov=src/py_netgear_plus tests

      - name: "Build packages"
        run: |
          python -m build
        if: contains(github.ref, 'refs/tags')

      - name: "Publish package on PyPi"
        uses: pypa/gh-action-pypi-publish@v1.12.4
        if: contains(github.ref, 'refs/tags')

      - name: "Create GitHub release"
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          tag: ${{ github.ref_name }}
        run: |
          if [[ "$tag" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
            echo "Create release $tag"
            gh release create "$tag" \
                --repo="$GITHUB_REPOSITORY" \
                --title="${GITHUB_REPOSITORY#*/} ${tag#v}" \
                --generate-notes
          elif [[ "$tag" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(pre|rc)[0-9]+$ ]]; then
            echo "Create prerelease $tag"
            gh release create "$tag" \
                --repo="$GITHUB_REPOSITORY" \
                --title="${GITHUB_REPOSITORY#*/} ${tag#v}" \
                --prerelease \
                --generate-notes
          else
            echo "Not releasing $tag"
          fi
