name: Publish to PyPI, TestPyPI, and GitHub

on:
  push:
  workflow_dispatch:
  
env:
  PROJECT_NAME: secretzero

concurrency:
  group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
  cancel-in-progress: true

permissions:
  contents: read

jobs:
  build:
    name: Build distribution
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
          persist-credentials: false

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

      - name: Install dependencies
        run: |
          pip install uv
          uv sync

      - name: Build package
        run: |
          uv build
      
      - name: Store the distribution packages
        uses: actions/upload-artifact@v4
        with:
          name: python-package-distributions
          path: dist/


  publish-to-testpypi:
    name: Publish to PyPI (TEST)
    needs:
    - build
    runs-on: ubuntu-latest
    if: startsWith(github.ref, 'refs/tags/')
    environment:
      name: testpypi
      url: https://test.pypi.org/p/${{ env.PROJECT_NAME }}
    permissions:
      id-token: write
    steps:
    - name: Download all the dists
      uses: actions/download-artifact@v4
      with:
        name: python-package-distributions
        path: dist/
    - name: Publish
      uses: pypa/gh-action-pypi-publish@release/v1
      with:
        repository-url: https://test.pypi.org/legacy/

  publish-to-pypi:
    name: Publish to PyPI (PROD)
    runs-on: ubuntu-latest
    # only publish to PyPI on tag pushes
    if: startsWith(github.ref, 'refs/tags/')
    needs: 
      - build
      - publish-to-testpypi
    permissions:
      id-token: write
    environment:
      name: production
      url: https://pypi.org/p/${{ env.PROJECT_NAME }}
    steps:
      - name: Download all the dists
        uses: actions/download-artifact@v4
        with:
          name: python-package-distributions
          path: dist/

      - name: Publish
        uses: pypa/gh-action-pypi-publish@release/v1

  create-release:
    name: Create GitHub Release
    permissions:
      contents: write
    runs-on: ubuntu-latest
    needs: publish-to-pypi
    if: github.ref_type == 'tag'
    steps:
      - name: Create Release
        uses: softprops/action-gh-release@v2
        with:
          files: dist/*
          make_latest: true
          generate_release_notes: true
