name: Publish to PyPI

on:
  release:
    types: [published]

permissions:
  contents: read

jobs:
  publish:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v4

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

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

      - name: Build package
        run: python -m build

      - name: Check distribution
        run: twine check dist/*

      - name: Dry-run install and verify version
        run: |
          pip install dist/veronica_cp-*.whl
          INSTALLED=$(python -c "import veronica; print(veronica.__version__)")
          TAG="${{ github.event.release.tag_name }}"
          TAG="${TAG#v}"
          EXPECTED=$(python -c "import re; print(re.split(r'-(?:rc|alpha|beta)', '$TAG')[0])")
          echo "Installed: $INSTALLED, Expected: $EXPECTED (tag: $TAG)"
          if [ "$INSTALLED" != "$EXPECTED" ]; then
            echo "::error::Version mismatch: installed=$INSTALLED expected=$EXPECTED"
            exit 1
          fi

      - name: Publish to PyPI
        if: ${{ !contains(github.event.release.tag_name, 'rc') && !contains(github.event.release.tag_name, 'alpha') && !contains(github.event.release.tag_name, 'beta') }}
        env:
          TWINE_USERNAME: __token__
          TWINE_PASSWORD: ${{ secrets.PYPI_API_TOKEN }}
        run: twine upload --skip-existing dist/*

      - name: Publish to TestPyPI (release candidates)
        if: ${{ contains(github.event.release.tag_name, 'rc') || contains(github.event.release.tag_name, 'alpha') || contains(github.event.release.tag_name, 'beta') }}
        env:
          TWINE_USERNAME: __token__
          TWINE_PASSWORD: ${{ secrets.TEST_PYPI_API_TOKEN }}
        run: twine upload --skip-existing --repository testpypi dist/*
