name: Publish to PyPI

on:
  push:
    tags:
      - 'v*'  # Triggers on version tags like v0.1.15
  workflow_dispatch:  # Allows manual triggering

jobs:
  test:
    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.11'
          
      - name: Install uv
        uses: astral-sh/setup-uv@v4
        with:
          enable-cache: true
          
      - name: Install dependencies and run tests
        run: |
          uv sync --extra dev
          uv run pytest tests/
          uv run ruff check .

  build:
    needs: test
    strategy:
      matrix:
        os: [ubuntu-latest, windows-latest, macos-latest]
        
    runs-on: ${{ matrix.os }}
    
    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        
      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.11'
          
      - name: Install Rust
        uses: dtolnay/rust-toolchain@stable
        
      - name: Update Rust dependencies
        run: cargo update
        
      - name: Build wheels
        uses: PyO3/maturin-action@v1
        with:
          command: build
          args: --release --out dist --interpreter python3.11
          manylinux: auto
          rust-toolchain: stable
          
      - name: Upload build artifacts
        uses: actions/upload-artifact@v4
        with:
          name: wheels-${{ matrix.os }}
          path: dist/

  build-sdist:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        
      - name: Build sdist
        uses: PyO3/maturin-action@v1
        with:
          command: sdist
          args: --out dist
          
      - name: Upload build artifacts
        uses: actions/upload-artifact@v4
        with:
          name: sdist
          path: dist/

  publish:
    needs: [test, build, build-sdist]
    runs-on: ubuntu-latest
    permissions:
      id-token: write  # Required for trusted publishing
      
    steps:
      - name: Download all artifacts
        uses: actions/download-artifact@v4
        with:
          pattern: "*"
          path: dist/
          merge-multiple: true
          
      - name: Publish to PyPI
        uses: pypa/gh-action-pypi-publish@release/v1
        with:
          print-hash: true
