name: Publish to PyPI

on:
  push:
    branches: [main]
  workflow_dispatch:

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
      - name: Install dependencies
        run: pip install -e ".[dev]"
      - name: Lint
        run: ruff check src/
      - name: Test
        run: pytest --tb=short -q

  publish:
    needs: test
    runs-on: ubuntu-latest
    permissions:
      id-token: write
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
      - name: Check if version already on PyPI
        id: check
        run: |
          VERSION=$(python -c "import tomllib; print(tomllib.load(open('pyproject.toml','rb'))['project']['version'])")
          echo "version=$VERSION" >> $GITHUB_OUTPUT
          HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" https://pypi.org/pypi/sandcastle-ai/$VERSION/json)
          if [ "$HTTP_CODE" = "200" ]; then
            echo "exists=true" >> $GITHUB_OUTPUT
            echo "Version $VERSION already on PyPI - skipping publish"
          else
            echo "exists=false" >> $GITHUB_OUTPUT
            echo "Version $VERSION not on PyPI - will publish"
          fi
      - name: Install build tools
        if: steps.check.outputs.exists == 'false'
        run: pip install build
      - name: Build package
        if: steps.check.outputs.exists == 'false'
        run: python -m build
      - name: Publish to PyPI
        if: steps.check.outputs.exists == 'false'
        uses: pypa/gh-action-pypi-publish@release/v1
