name: Build Base Docker Image

# Build base image only when requirements.txt changes or manually triggered
on:
  push:
    branches:
      - main
    paths:
      - 'backend/requirements.txt'
      - 'backend/Dockerfile.base'
  workflow_dispatch:  # Allow manual trigger

env:
  REGISTRY: git.benoitsz.com
  IMAGE_BASE: audio-classifier-base

jobs:
  build-base:
    name: Build Base Image
    runs-on: ubuntu-latest

    steps:
      - name: Checkout code
        uses: actions/checkout@v4

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

      - name: Login to Gitea Container Registry
        uses: docker/login-action@v3
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ gitea.actor }}
          password: ${{ secrets.REGISTRY_TOKEN }}

      - name: Extract metadata
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: ${{ env.REGISTRY }}/${{ gitea.repository_owner }}/${{ env.IMAGE_BASE }}
          tags: |
            type=raw,value=latest
            type=sha,prefix=sha-,format=short

      - name: Build and push base image
        uses: docker/build-push-action@v5
        with:
          context: ./backend
          file: ./backend/Dockerfile.base
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          cache-from: type=registry,ref=${{ env.REGISTRY }}/${{ gitea.repository_owner }}/${{ env.IMAGE_BASE }}:buildcache
          cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ gitea.repository_owner }}/${{ env.IMAGE_BASE }}:buildcache,mode=max
          platforms: linux/amd64

      - name: Image built successfully
        run: |
          echo "✅ Base image built and pushed successfully"
          echo "📦 Image: ${{ env.REGISTRY }}/${{ gitea.repository_owner }}/${{ env.IMAGE_BASE }}:latest"
          echo "⏱️  This image will be used by the main backend builds to speed up CI/CD"
