name: Build and Push MCP Server Docker Image

on:
  push:
    paths:
      - "mcp_server/pyproject.toml"
    branches:
      - main
  pull_request:
    paths:
      - "mcp_server/pyproject.toml"
    branches:
      - main
  workflow_dispatch:
    inputs:
      push_image:
        description: "Push image to registry (unchecked for testing)"
        required: false
        default: false
        type: boolean

env:
  REGISTRY: docker.io
  IMAGE_NAME: zepai/knowledge-graph-mcp

jobs:
  build-and-push:
    runs-on: depot-ubuntu-24.04-small
    environment: development
    permissions:
      contents: read
      id-token: write
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Extract version from pyproject.toml
        id: version
        run: |
          VERSION=$(python -c "import tomllib; print(tomllib.load(open('mcp_server/pyproject.toml', 'rb'))['project']['version'])")
          echo "version=$VERSION" >> $GITHUB_OUTPUT
          echo "tag=v$VERSION" >> $GITHUB_OUTPUT
      - name: Log in to Docker Hub
        if: github.event_name != 'pull_request' && (github.event_name != 'workflow_dispatch' || inputs.push_image)
        uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ secrets.DOCKERHUB_USERNAME }}
          password: ${{ secrets.DOCKERHUB_TOKEN }}

      - name: Set up Depot CLI
        uses: depot/setup-action@v1

      - name: Extract metadata
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
          tags: |
            type=ref,event=branch
            type=ref,event=pr
            type=raw,value=${{ steps.version.outputs.tag }}
            type=raw,value=latest,enable={{is_default_branch}}

      - name: Depot build and push image
        uses: depot/build-push-action@v1
        with:
          project: v9jv1mlpwc
          context: ./mcp_server
          platforms: linux/amd64,linux/arm64
          push: ${{ github.event_name != 'pull_request' && (github.event_name != 'workflow_dispatch' || inputs.push_image) }}
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
