name: Release

on:
  push:
    branches: [main]
  workflow_dispatch:

jobs:
  test:
    runs-on: ubuntu-latest
    env:
      PYTHON_VERSION: "3.13"
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - uses: astral-sh/setup-uv@v3
      - run: uv python install $PYTHON_VERSION
      - run: uv run --python $PYTHON_VERSION python -c "import sys; print(sys.version)"
      - run: uv sync --group dev --python $PYTHON_VERSION
      - run: uv run --python $PYTHON_VERSION ruff check src tests
      - run: uv run --python $PYTHON_VERSION pyright
      - run: uv run --python $PYTHON_VERSION pytest

  release:
    needs: test
    runs-on: ubuntu-latest
    if: github.ref == 'refs/heads/main'
    concurrency: release
    environment: release
    env:
      PYTHON_VERSION: "3.13"
    permissions:
      id-token: write
      contents: write

    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
          token: ${{ secrets.GITHUB_TOKEN }}

      - name: Install uv
        uses: astral-sh/setup-uv@v3

      - name: Set up Python
        run: uv python install $PYTHON_VERSION

      - name: Install dependencies
        run: uv sync --group dev --python $PYTHON_VERSION

      - name: Python Semantic Release
        id: release
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          uv run --python $PYTHON_VERSION semantic-release version --no-push
          if [ -f dist/*.whl ]; then
            echo "released=true" >> $GITHUB_OUTPUT
          else
            echo "released=false" >> $GITHUB_OUTPUT
          fi

      - name: Push changes
        if: steps.release.outputs.released == 'true'
        run: |
          git push origin main --tags

      - name: Publish to PyPI
        if: steps.release.outputs.released == 'true'
        run: uv publish --trusted-publishing always
