# This workflow will upload a Python Package using Twine when a release is created
# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python#publishing-to-package-registries

# This workflow uses actions that are not certified by GitHub.
# They are provided by a third-party and are governed by
# separate terms of service, privacy policy, and support
# documentation.

name: publish

on:
  release:
    types: [published]     # publish full release to PyPI when a release is created on Github
  schedule:
    - cron: "0 17 * * FRI" # tag a pre-release on Github every Friday at 5 PM UTC

permissions:
  contents: write
  id-token: write

jobs:
  tag_pre_release:
    if: github.event_name == 'schedule'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Create pre-release tag
        run: |
          git fetch --tags
          latest_tag=$(git tag --list --sort=-v:refname | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+rc[0-9]+$' | head -n 1)
          if [ -z "$latest_tag" ]; then
            new_tag="v0.1.0rc1"
          else
            new_tag=$(echo $latest_tag | awk -F'rc' '{print $1 "rc" $2+1}')
          fi
          git tag $new_tag
          git push origin $new_tag

  publish_to_pypi:
    if: github.event_name == 'release'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: "3.x"
      - uses: astral-sh/setup-uv@v5
      - run: uv run ruff check --no-fix --select PLE # check only for syntax errors
      - run: uv build
      - run: uv run --isolated --no-project --with pytest --with dist/*.whl tests/conftest.py
      - run: uv run --isolated --no-project --with pytest --with dist/*.tar.gz tests/conftest.py
      - run: uv run --with=dotenv pytest \
          --ignore=tests/test_dropdown_error.py \
          --ignore=tests/test_gif_path.py \
          --ignore=tests/test_models.py \
          --ignore=tests/test_react_dropdown.py \
          --ignore=tests/test_save_conversation.py \
          --ignore=tests/test_vision.py \
          --ignore=tests/test_wait_for_element.py || true
      - run: uv publish --trusted-publishing always
      - name: Push to stable branch (if stable release)
        if: startsWith(github.ref_name, 'v') && !contains(github.ref_name, 'rc')
        run: |
          git checkout -b stable
          git push origin stable
