name: Release

on:
  push:
    tags:
      - "v*"

permissions:
  contents: write
  id-token: write  # Required for Sigstore OIDC signing

env:
  FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true

jobs:
  build:
    name: Build distribution
    runs-on: ubuntu-latest
    permissions:
      contents: read
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"

      - name: Install build tools
        run: pip install hatchling build

      - name: Build sdist and wheel
        run: python -m build

      - name: Upload build artifacts
        uses: actions/upload-artifact@v4
        with:
          name: dist
          path: dist/
          retention-days: 5

  sign:
    name: Sign with Sigstore
    runs-on: ubuntu-latest
    needs: build
    permissions:
      id-token: write  # OIDC for Sigstore
    steps:
      - name: Download build artifacts
        uses: actions/download-artifact@v4
        with:
          name: dist
          path: dist/

      - name: Sign with Sigstore
        uses: sigstore/gh-action-sigstore-python@v3
        with:
          inputs: >-
            ./dist/*.tar.gz
            ./dist/*.whl

      - name: Upload signed artifacts
        uses: actions/upload-artifact@v4
        with:
          name: dist-signed
          path: dist/
          retention-days: 5

  publish-pypi:
    name: Publish to PyPI
    runs-on: ubuntu-latest
    needs: sign
    environment: pypi
    permissions:
      id-token: write  # OIDC trusted publisher
    steps:
      - name: Download signed artifacts
        uses: actions/download-artifact@v4
        with:
          name: dist-signed
          path: dist/

      - name: Publish to PyPI
        uses: pypa/gh-action-pypi-publish@release/v1
        with:
          skip-existing: true

  github-release:
    name: Create GitHub Release
    runs-on: ubuntu-latest
    needs: sign
    permissions:
      contents: write
    steps:
      - name: Download signed artifacts
        uses: actions/download-artifact@v4
        with:
          name: dist-signed
          path: dist/

      - name: Create GitHub Release
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          TAG="${GITHUB_REF#refs/tags/}"
          gh release create "$TAG" \
            --repo "$GITHUB_REPOSITORY" \
            --title "AASTF $TAG" \
            --generate-notes \
            dist/*
