name: Distribution

on:
  push:
    branches:
      - production

permissions:
  contents: write
  packages: write

jobs:
  release:
    name: GitHub Release
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.10'
          cache: 'pip'

      - name: Install hatch
        run: pip install hatch

      - name: Get version
        id: get_version
        run: echo "VERSION=$(hatch version)" >> $GITHUB_OUTPUT

      - name: Build wheel and source dist
        run: hatch build

      - name: Create Release
        uses: softprops/action-gh-release@v1
        with:
          tag_name: v${{ steps.get_version.outputs.VERSION }}
          files: |
            dist/*.whl
            dist/*.tar.gz
          generate_release_notes: true
          draft: false
          prerelease: false
        continue-on-error: true # Skip if release already exists

  pypi-publish:
    name: Upload to PyPI
    runs-on: ubuntu-latest
    needs: release
    environment:
      name: pypi
      url: https://pypi.org/p/candlekeep
    permissions:
      id-token: write
    steps:
      - uses: actions/checkout@v4
      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.10'
      - name: Install hatch
        run: pip install hatch
      - name: Build
        run: hatch build
      - name: Publish to PyPI
        uses: pypa/gh-action-pypi-publish@release/v1
        with:
          skip-existing: true

  docker:
    name: GitHub Packages (GHCR)
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Log in to GHCR
        uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Extract metadata (tags, labels) for Docker
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: ghcr.io/${{ github.repository }}
          tags: |
            type=pep440,pattern={{version}}
            type=raw,value=latest

      - name: Build and push Docker image
        uses: docker/build-push-action@v5
        with:
          context: .
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          cache-from: type=gha
          cache-to: type=gha,mode=max
