name: Worker Base Image Build

on:
  push:
    branches:
      - develop
      - main
    paths:
      - 'requirements-base.txt'
      - 'requirements-worker.txt'
      - 'infra/docker/worker-base-builder.Dockerfile'
      - 'infra/docker/worker-base-runtime.Dockerfile'
  workflow_dispatch:  # 支持手动触发

jobs:
  build-worker-base:
    name: Build Worker Base Images
    runs-on: runtime-builder
    timeout-minutes: 30
    strategy:
      fail-fast: false
      matrix:
        include:
        - name: builder
          dockerfile: infra/docker/worker-base-builder.Dockerfile
          image_name: worker-base-builder
          cache_name: worker-base-builder-cache
        - name: runtime
          dockerfile: infra/docker/worker-base-runtime.Dockerfile
          image_name: worker-base-runtime
          cache_name: worker-base-runtime-cache
    steps:
    - name: Checkout code
      shell: sh
      env:
        GITHUB_TOKEN: ${{ github.token }}
      run: |
        curl -sH "Authorization: token $GITHUB_TOKEN"           "${GITHUB_API_URL}/repos/${GITHUB_REPOSITORY}/raw/scripts/ci/step_checkout.sh?ref=${GITHUB_SHA}"           | bash

    - name: Docker login to Registry
      shell: sh
      env:
        ACR_USERNAME: ${{ secrets.ACR_USERNAME }}
        ACR_PASSWORD: ${{ secrets.ACR_PASSWORD }}
        GITEA_REGISTRY_USER: xiaoxia
        GITEA_REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}
      run: |
        set -eu
        for i in 1 2 3; do
          echo "=== Docker login 尝试 $i/3 ==="
          if printf '%s' "${ACR_PASSWORD}" | docker login xiaoxia-registry.cn-hangzhou.cr.aliyuncs.com -u "${ACR_USERNAME}" --password-stdin              && docker login git.xiaoxiajianji.com -u "${GITEA_REGISTRY_USER}" -p "${GITEA_REGISTRY_TOKEN}"; then
            echo "✅ Docker login successful"
            break
          fi
          echo "❌ Docker login 失败（尝试 $i/3），5s 后重试..."
          sleep 5
        done

    - name: Setup buildx builder
      shell: sh
      run: |
        set -eu
        BUILDER_NAME="ci-builder-${GITHUB_RUN_ID}-${{ matrix.name }}"
        if ! docker buildx inspect "$BUILDER_NAME" > /dev/null 2>&1; then
          docker buildx create --use --name "$BUILDER_NAME" --driver docker-container
          echo "Created $BUILDER_NAME"
        else
          docker buildx use "$BUILDER_NAME"
          echo "Using existing $BUILDER_NAME"
        fi
        docker buildx inspect --bootstrap

    - name: Build and push base image
      shell: sh
      run: |
        set -eu
        REGISTRY="xiaoxia-registry.cn-hangzhou.cr.aliyuncs.com/xiaoxiakeji"
        IMAGE_TAG="${REGISTRY}/${{ matrix.image_name }}:latest"
        SAFE_REF_NAME=$(echo "${GITHUB_REF_NAME}" | tr '/' '-')
        CACHE_REF="${REGISTRY}/${{ matrix.cache_name }}:${SAFE_REF_NAME}"
        
        echo "=== Building ${{ matrix.name }} base image ==="
        echo "Image: ${IMAGE_TAG}"
        echo "Cache: ${CACHE_REF}"
        
        # 用通用构建脚本
        bash scripts/ci/docker_build_push.sh           ${{ matrix.dockerfile }}           "${IMAGE_TAG}"           "${CACHE_REF}"
        
        # 同时推送到 Gitea Packages 作为备份（可选）
        GITEA_IMAGE="git.xiaoxiajianji.com/xiaoxia-saas/${{ matrix.image_name }}:latest"
        docker tag "${IMAGE_TAG}" "${GITEA_IMAGE}"
        docker push "${GITEA_IMAGE}" || echo "Gitea Packages push failed (non-fatal)"
        
        echo ""
        echo "✅ ${{ matrix.name }} base image built and pushed"

    - name: Cleanup buildx builder
      if: always()
      shell: sh
      run: |
        docker buildx rm "ci-builder-${GITHUB_RUN_ID}-${{ matrix.name }}" 2>/dev/null || true
        docker buildx prune -f 2>/dev/null || true
        echo "Builder cleanup done"
