name: 🐳 Build & Push Docker Image

on:
  workflow_call:
    inputs:
      tag:
        description: "Release tag"
        required: true
        type: string

env:
  GHCR_REGISTRY: ghcr.io
  GHCR_IMAGE_NAME: ${{ github.repository_owner }}/picoclaw
  DOCKERHUB_REGISTRY: docker.io
  DOCKERHUB_IMAGE_NAME: ${{ vars.DOCKERHUB_REPOSITORY }}

jobs:
  build:
    name: 🏗️ Build Docker Image
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write

    steps:
      # ── Checkout ──────────────────────────────
      - name: 📥 Checkout repository
        uses: actions/checkout@v6
        with:
          ref: ${{ inputs.tag }}

      # ── Docker Buildx ─────────────────────────
      - name: 🔧 Set up Docker Buildx
        uses: docker/setup-buildx-action@v4

      # ── Login to GHCR ─────────────────────────
      - name: 🔑 Login to GitHub Container Registry
        uses: docker/login-action@v4
        with:
          registry: ${{ env.GHCR_REGISTRY }}
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      # ── Login to Docker Hub ────────────────────
      - name: 🔑 Login to Docker Hub
        uses: docker/login-action@v4
        with:
          registry: ${{ env.DOCKERHUB_REGISTRY }}
          username: ${{ secrets.DOCKERHUB_USERNAME }}
          password: ${{ secrets.DOCKERHUB_TOKEN }}

      # ── Metadata (tags & labels) ──────────────
      - name: 🏷️ Prepare image tags
        id: tags
        shell: bash
        run: |
          tag="${{ inputs.tag }}"
          echo "ghcr_tag=${{ env.GHCR_REGISTRY }}/${{ env.GHCR_IMAGE_NAME }}:${tag}" >> "$GITHUB_OUTPUT"
          echo "ghcr_latest=${{ env.GHCR_REGISTRY }}/${{ env.GHCR_IMAGE_NAME }}:latest" >> "$GITHUB_OUTPUT"
          echo "dockerhub_tag=${{ env.DOCKERHUB_REGISTRY }}/${{ env.DOCKERHUB_IMAGE_NAME }}:${tag}" >> "$GITHUB_OUTPUT"
          echo "dockerhub_latest=${{ env.DOCKERHUB_REGISTRY }}/${{ env.DOCKERHUB_IMAGE_NAME }}:latest" >> "$GITHUB_OUTPUT"

      # ── Build & Push ──────────────────────────
      - name: 🚀 Build and push Docker image
        uses: docker/build-push-action@v7
        with:
          context: .
          push: true
          tags: |
            ${{ steps.tags.outputs.ghcr_tag }}
            ${{ steps.tags.outputs.ghcr_latest }}
            ${{ steps.tags.outputs.dockerhub_tag }}
            ${{ steps.tags.outputs.dockerhub_latest }}
          cache-from: type=gha
          cache-to: type=gha,mode=max
          platforms: linux/amd64,linux/arm64,linux/riscv64
