name: Release

on:
  push:
    tags:
      - '*'  # Trigger with any tag

jobs:
  release:
    if: startsWith(github.ref, 'refs/tags/')
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Set up Python
        uses: actions/setup-python@v4
        with:
          python-version: 3.12

      - name: Install build tools
        run: python -m pip install --upgrade pip build twine toml

      - name: Validate tag and update pyproject.toml
        id: version
        run: |
          TAG=${GITHUB_REF#refs/tags/}
          echo "Tag: $TAG"
          python .github/scripts/update_version.py

      - name: Build package
        run: python -m build

      - name: Publish to PyPI/TestPyPI
        env:
          TWINE_USERNAME: __token__
          TWINE_PASSWORD: {% raw %}${{ secrets.PYPI_API_TOKEN }}{% endraw %}
          TWINE_PASSWORD_TEST: {% raw %}${{ secrets.TEST_PYPI_API_TOKEN }}{% endraw %}
        run: |
          TAG=${GITHUB_REF#refs/tags/}
          if [[ "$TAG" == test-* ]]; then
              echo "Publishing to TestPyPI"
              python -m twine upload --repository-url https://test.pypi.org/legacy/ dist/* -u __token__ -p $TWINE_PASSWORD_TEST
          else
              echo "Publishing to PyPI"
              python -m twine upload dist/* -u __token__ -p $TWINE_PASSWORD

