name: Publish to Docker Hub

on:
  release:
    types: [published]
  workflow_dispatch:
    inputs:
      version:
        description: "Version tag to build (e.g. 2.6.0)"
        required: true
        type: string

permissions:
  contents: read

jobs:
  docker:
    name: Build and Push Docker (multi-arch)
    runs-on: ubuntu-latest
    env:
      IMAGE_NAME: diegosouzapw/omniroute
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          ref: ${{ github.event_name == 'workflow_dispatch' && format('refs/tags/v{0}', inputs.version) || '' }}

      - name: Set up QEMU (for multi-arch builds)
        uses: docker/setup-qemu-action@v3

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

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

      - name: Extract version from release tag or input
        id: version
        run: |
          if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
            VERSION="${{ inputs.version }}"
          else
            VERSION="${GITHUB_REF_NAME}"
            VERSION="${VERSION#v}"
          fi
          echo "version=$VERSION" >> "$GITHUB_OUTPUT"
          echo "Publishing Docker image: $IMAGE_NAME:$VERSION"

      - name: Build and push multi-arch image
        uses: docker/build-push-action@v6
        with:
          context: .
          target: runner-base
          platforms: linux/amd64,linux/arm64
          push: true
          tags: |
            ${{ env.IMAGE_NAME }}:${{ steps.version.outputs.version }}
            ${{ env.IMAGE_NAME }}:latest
          cache-from: type=gha
          cache-to: type=gha,mode=max
          no-cache: false
        env:
          DOCKER_BUILDKIT_INLINE_CACHE: 1

      - name: Inspect image
        run: |
          docker buildx imagetools inspect "${{ env.IMAGE_NAME }}:${{ steps.version.outputs.version }}"

      - name: Update Docker Hub description
        uses: peter-evans/dockerhub-description@v4
        with:
          username: ${{ secrets.DOCKERHUB_USERNAME }}
          password: ${{ secrets.DOCKERHUB_TOKEN }}
          repository: diegosouzapw/omniroute
          short-description: "OmniRoute — Unified AI proxy. Route any LLM through one endpoint."
          readme-filepath: ./README.md
