name: Docker Image

on:
  push:
    tags:
      - "v*"

permissions:
  contents: read

env:
  IMAGE_NAME: mlogclub/agent-desk

jobs:
  build:
    name: Build and push Docker image
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Validate Docker Hub credentials
        env:
          DOCKERHUB_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }}
          DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }}
        run: |
          if [ -z "${DOCKERHUB_USERNAME}" ]; then
            echo "Secret DOCKERHUB_USERNAME is required" >&2
            exit 1
          fi
          if [ -z "${DOCKERHUB_TOKEN}" ]; then
            echo "Secret DOCKERHUB_TOKEN is required" >&2
            exit 1
          fi

      - name: Set up QEMU
        uses: docker/setup-qemu-action@v3

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

      - name: Log in to Docker Hub
        uses: docker/login-action@v3
        with:
          username: ${{ secrets.DOCKERHUB_USERNAME }}
          password: ${{ secrets.DOCKERHUB_TOKEN }}

      - name: Extract Docker metadata
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: ${{ env.IMAGE_NAME }}
          tags: |
            type=ref,event=tag
            type=semver,pattern={{version}}
            type=semver,pattern={{major}}.{{minor}}
            type=raw,value=latest,enable=${{ !contains(github.ref_name, '-') }}

      - name: Extract LanceDB Docker metadata
        id: meta-lancedb
        uses: docker/metadata-action@v5
        with:
          images: ${{ env.IMAGE_NAME }}
          tags: |
            type=ref,event=tag
            type=semver,pattern={{version}}
            type=semver,pattern={{major}}.{{minor}}
            type=raw,value=latest,enable=${{ !contains(github.ref_name, '-') }}
          flavor: |
            suffix=-lancedb,onlatest=true

      - name: Build and push
        uses: docker/build-push-action@v6
        with:
          context: .
          target: app
          platforms: linux/amd64
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}

      - name: Build and push LanceDB
        uses: docker/build-push-action@v6
        with:
          context: .
          target: app-lancedb
          platforms: linux/amd64
          push: true
          tags: ${{ steps.meta-lancedb.outputs.tags }}
          labels: ${{ steps.meta-lancedb.outputs.labels }}
