name: release-main

permissions:
  contents: write
  packages: write

on:
  release:
    types: [published]

jobs:
  set-version:
    runs-on: ubuntu-24.04
    steps:
      - uses: actions/checkout@v4

      - name: Export tag
        id: vars
        run: echo tag=${GITHUB_REF#refs/*/} >> $GITHUB_OUTPUT
        if: ${{ github.event_name == 'release' }}

      - name: Update project version
        run: |
          sed -i "s/^version = \".*\"/version = \"$RELEASE_VERSION\"/" pyproject.toml
        env:
          RELEASE_VERSION: ${{ steps.vars.outputs.tag }}
        if: ${{ github.event_name == 'release' }}

      - name: Upload updated pyproject.toml
        uses: actions/upload-artifact@v4
        with:
          name: pyproject-toml
          path: pyproject.toml

  publish:
    runs-on: ubuntu-latest
    needs: [set-version]
    steps:
      - name: Check out
        uses: actions/checkout@v4

      - name: Set up the environment
        uses: ./.github/actions/setup-python-env

      - name: Download updated pyproject.toml
        uses: actions/download-artifact@v4
        with:
          name: pyproject-toml

      - name: Build package
        run: uv build

      - name: Publish package
        run: uv publish
        env:
          UV_PUBLISH_TOKEN: ${{ secrets.PYPI_TOKEN }}

      - name: Upload dists to release
        uses: svenstaro/upload-release-action@v2
        with:
            repo_token: ${{ secrets.GITHUB_TOKEN }}
            file: dist/*
            file_glob: true
            tag: ${{ github.ref }}
            overwrite: true


  push-image:
    runs-on: ubuntu-latest
    needs: [set-version]
    steps:
      - uses: actions/checkout@v4
      - name: Export tag
        id: vars
        run: echo tag=${GITHUB_REF#refs/*/} >> $GITHUB_OUTPUT
        if: ${{ github.event_name == 'release' }}
      - name: Set up QEMU
        uses: docker/setup-qemu-action@v3
      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3
      - name: Login to Github Container Registry
        uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ai-zerolab
          password: ${{ secrets.GITHUB_TOKEN }}
      - name: Build and push image
        id: docker_build_publish
        uses: docker/build-push-action@v5
        with:
            context: .
            platforms: linux/amd64,linux/arm64/v8
            cache-from: type=gha
            cache-to: type=gha,mode=max
            file: ./Dockerfile
            push: true
            tags: |
              ghcr.io/ai-zerolab/yourware-mcp:${{ steps.vars.outputs.tag }}
              ghcr.io/ai-zerolab/yourware-mcp:latest
