# DevContainer Variants Build & Test CI
# ======================================
# Builds devcontainer-base main image (conda-libmamba-ft) and variants in dependency order:
#   main (conda+Python3.14.6 cp314t free-threading+libmamba) → conda → conda-llvm → onnx-pytorch → onnx-quantized
#
# Architecture:
#   - lint job: fast feedback (bash syntax, Dockerfile checks)
#   - build-main job: build the new main image (Dockerfile with integrated conda+Python3.14+libmamba)
#   - build-variants job: build variant images on top of main (experimental, Python 3.14 compat WIP)
#   - push job: push images to registry (main branch only, when secrets configured)
#
# Triggers:
#   - Pull Request: Lint + main image build & test (< 20min fast feedback)
#   - Push to main: Full build + test + push
#   - Nightly (00:00 UTC / 08:00 Beijing): Full build + test + benchmarks
#   - Manual: Select variant/mirror/cache/registry options
#
# Registry Configuration (GitHub Secrets):
#   REGISTRY_URL       - e.g., ghcr.io, your-registry.example.com (default: ghcr.io)
#   REGISTRY_USERNAME  - registry username
#   REGISTRY_PASSWORD  - registry password/token
#
# See design doc: apps/docker-images/devcontainer-base/.agents/workflows/variants-ci.md

name: DevContainer CI

on:
  pull_request:
    branches: [main]
    paths:
      - 'apps/docker-images/devcontainer-base/Dockerfile'
      - 'apps/docker-images/devcontainer-base/entrypoint.sh'
      - 'apps/docker-images/devcontainer-base/scripts/**'
      - 'apps/docker-images/devcontainer-base/examples/**'
      - 'apps/docker-images/devcontainer-base/config/**'
      - 'apps/docker-images/devcontainer-base/variants/**'
      - 'apps/docker-images/devcontainer-base/.agents/**'
      - '.github/workflows/devcontainer-variants.yml'

  push:
    branches: [main]
    paths:
      - 'apps/docker-images/devcontainer-base/Dockerfile'
      - 'apps/docker-images/devcontainer-base/entrypoint.sh'
      - 'apps/docker-images/devcontainer-base/scripts/**'
      - 'apps/docker-images/devcontainer-base/examples/**'
      - 'apps/docker-images/devcontainer-base/config/**'
      - 'apps/docker-images/devcontainer-base/variants/**'
      - 'apps/docker-images/devcontainer-base/.agents/**'
      - '.github/workflows/devcontainer-variants.yml'

  schedule:
    - cron: '0 0 * * *'  # Daily at 00:00 UTC (08:00 Beijing)

  workflow_dispatch:
    inputs:
      build_variants:
        description: 'Build variant images (conda-llvm/onnx-pytorch/onnx-quantized)'
        required: false
        default: false
        type: boolean
      mirror:
        description: 'Mirror source (CI runners are overseas; official usually fastest)'
        required: true
        default: 'official'
        type: choice
        options:
          - official
          - cn
      no_cache:
        description: 'Disable build cache'
        required: false
        default: false
        type: boolean
      push_registry:
        description: 'Push images to registry (requires secrets)'
        required: false
        default: true
        type: boolean

env:
  PROJECT_DIR: apps/docker-images/devcontainer-base
  IMAGE_TAG: ci-${{ github.sha }}
  REGISTRY_URL: ${{ secrets.REGISTRY_URL || 'ghcr.io' }}
  REGISTRY_NAMESPACE: ${{ secrets.REGISTRY_NAMESPACE || github.repository_owner }}

jobs:
  # ──────────────────────────────────────────────────────────────────────
  # Stage 0: Lint & Validate (all triggers)
  # ──────────────────────────────────────────────────────────────────────
  lint:
    name: Lint & Validate
    runs-on: ubuntu-latest
    timeout-minutes: 5
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Print environment info
        run: |
          echo "============================================================"
          echo "=== STAGE: Lint & Validate - Environment Information     ==="
          echo "============================================================"
          echo "Runner OS:     $(uname -a)"
          echo "Date (UTC):    $(date -u '+%Y-%m-%d %H:%M:%S UTC')"
          echo "GitHub SHA:    ${{ github.sha }}"
          echo "GitHub ref:    ${{ github.ref }}"
          echo "Event name:    ${{ github.event_name }}"
          echo "============================================================"

      - name: Check bash scripts syntax (bash -n)
        working-directory: ${{ env.PROJECT_DIR }}
        run: |
          echo ""
          echo "=== STEP: Bash script syntax check (bash -n) ==="
          echo ""
          fail_count=0
          pass_count=0
          while IFS= read -r -d '' script; do
            if bash -n "$script" 2>&1; then
              echo "  ✅ PASS: $script"
              pass_count=$((pass_count + 1))
            else
              echo "  ❌ FAIL: $script"
              fail_count=$((fail_count + 1))
            fi
          done < <(find scripts/ variants/ examples/ -name "*.sh" -type f -print0 2>/dev/null)
          echo ""
          echo "  Result: $pass_count passed, $fail_count failed"
          if [ "$fail_count" -gt 0 ]; then
            echo "  ❌ Syntax check FAILED"
            exit 1
          fi
          echo "  ✅ All bash scripts pass syntax check"

      - name: Check Python scripts syntax
        working-directory: ${{ env.PROJECT_DIR }}
        run: |
          echo ""
          echo "=== STEP: Python script syntax check ==="
          echo ""
          fail_count=0
          pass_count=0
          while IFS= read -r -d '' pyfile; do
            if python3 -c "import py_compile; py_compile.compile('$pyfile', doraise=True)" 2>&1; then
              echo "  ✅ PASS: $pyfile"
              pass_count=$((pass_count + 1))
            else
              echo "  ❌ FAIL: $pyfile"
              fail_count=$((fail_count + 1))
            fi
          done < <(find scripts/ examples/ -name "*.py" -type f -print0 2>/dev/null)
          echo ""
          echo "  Result: $pass_count passed, $fail_count failed"
          if [ "$fail_count" -gt 0 ]; then
            echo "  ❌ Python syntax check FAILED"
            exit 1
          fi
          echo "  ✅ All Python scripts pass syntax check"

      - name: Validate build.sh timer parser
        working-directory: ${{ env.PROJECT_DIR }}
        run: |
          echo ""
          echo "=== STEP: Timer parser unit tests ==="
          echo ""
          if [ -f variants/scripts/test-timer-parser.sh ]; then
            bash variants/scripts/test-timer-parser.sh
          else
            echo "  ⚠️  test-timer-parser.sh not found, skipping"
          fi

      - name: Check Dockerfile syntax (structure validation)
        working-directory: ${{ env.PROJECT_DIR }}
        run: |
          echo ""
          echo "=== STEP: Dockerfile structure validation ==="
          echo ""
          fail_count=0
          dockerfiles_found=0
          for dockerfile in Dockerfile variants/*/Dockerfile; do
            if [ ! -f "$dockerfile" ]; then
              continue
            fi
            dockerfiles_found=$((dockerfiles_found + 1))
            echo "  Checking: $dockerfile"
            ok=true
            # Must have syntax declaration
            if ! grep -q "^# syntax=" "$dockerfile"; then
              echo "    ❌ Missing # syntax= directive"
              ok=false
            fi
            # Must have SHELL instruction
            if ! grep -q "^SHELL" "$dockerfile"; then
              echo "    ❌ Missing SHELL instruction"
              ok=false
            fi
            # Must re-declare ARG BASE_TAG after FROM (variant Dockerfiles only)
            if echo "$dockerfile" | grep -q "variants/.*Dockerfile"; then
              after_from=$(awk '/^FROM/{found=1} found{print}' "$dockerfile")
              if ! echo "$after_from" | grep -q "ARG BASE_TAG"; then
                echo "    ❌ Missing ARG BASE_TAG after FROM"
                ok=false
              fi
            fi
            # Main Dockerfile must include Python 3.14 and libmamba setup
            if [ "$dockerfile" = "Dockerfile" ]; then
              if ! grep -q "python=3.14\|python 3.14" "$dockerfile"; then
                echo "    ❌ Main Dockerfile missing Python 3.14 installation"
                ok=false
              fi
              if ! grep -q "libmamba\|conda-libmamba-solver" "$dockerfile"; then
                echo "    ❌ Main Dockerfile missing libmamba solver configuration"
                ok=false
              fi
            fi
            if $ok; then
              echo "    ✅ OK"
            else
              fail_count=$((fail_count + 1))
            fi
          done
          echo ""
          echo "  Checked $dockerfiles_found Dockerfile(s)"
          if [ "$fail_count" -gt 0 ]; then
            echo "  ❌ $fail_count Dockerfile(s) have issues"
            exit 1
          fi
          echo "  ✅ All Dockerfiles pass structure validation"

      - name: Lint summary
        if: always()
        run: |
          echo ""
          echo "============================================================"
          echo "=== STAGE: Lint & Validate - COMPLETE                    ==="
          echo "=== Status: ${{ job.status }}                                         ==="
          echo "============================================================"

  # ──────────────────────────────────────────────────────────────────────
  # Stage 1: Build & Test Main Image (conda-libmamba-ft, default cp314t)
  # ──────────────────────────────────────────────────────────────────────
  build-main:
    name: Build & Test Main Image
    runs-on: ubuntu-latest
    needs: lint
    timeout-minutes: 60
    outputs:
      image_tag: ${{ env.IMAGE_TAG }}
    env:
      BUILD_LOG_DIR: /tmp/build-logs
      MIRROR_FLAG: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.mirror == 'cn' && '--cn' || '' }}
      NO_CACHE_FLAG: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.no_cache && '--no-cache' || '' }}
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Print CI environment & build configuration
        run: |
          echo "============================================================"
          echo "=== STAGE: Build Main Image - Environment                ==="
          echo "============================================================"
          echo ""
          echo "Date (UTC):     $(date -u '+%Y-%m-%d %H:%M:%S UTC')"
          echo "Runner OS:      $(uname -a)"
          echo "CPU cores:      $(nproc)"
          echo "Memory:         $(free -h | grep Mem | awk '{print $2}') total"
          echo "Disk:           $(df -h / | tail -1 | awk '{print $4}') available"
          echo ""
          echo "Project dir:    ${{ env.PROJECT_DIR }}"
          echo "Image tag:      ${{ env.IMAGE_TAG }}"
          echo "Mirror flag:    ${MIRROR_FLAG:-official}"
          echo "No-cache:       ${NO_CACHE_FLAG:-cache enabled}"
          echo "Registry URL:   ${{ env.REGISTRY_URL }}"
          echo ""
          echo "--- Docker Information ---"
          docker --version
          docker buildx version
          echo ""
          echo "============================================================"
          mkdir -p "$BUILD_LOG_DIR"

      - name: Set up Docker Buildx
        run: |
          echo ""
          echo "=== STEP: Setup Docker Buildx ==="
          docker run --privileged --rm tonistiigi/binfmt --install all 2>&1 | tail -5 || true
          echo "✅ Buildx setup complete"

      - name: Build main image (conda-libmamba-ft, default cp314t)
        id: build_main
        working-directory: ${{ env.PROJECT_DIR }}
        run: |
          echo ""
          echo "╔══════════════════════════════════════════════════════════════╗"
          echo "║  BUILD: Main Image (conda-libmamba-ft, Python 3.14.6 cp314t)║"
          echo "╚══════════════════════════════════════════════════════════════╝"
          echo ""
          echo "Command: bash scripts/build.sh --tag ${{ env.IMAGE_TAG }} ${MIRROR_FLAG} ${NO_CACHE_FLAG}"
          STAGE_START=$(date +%s)
          echo "Start time: $(date -u '+%Y-%m-%d %H:%M:%S UTC')"
          echo ""
          set -o pipefail
          bash scripts/build.sh --tag ${{ env.IMAGE_TAG }} ${MIRROR_FLAG} ${NO_CACHE_FLAG} 2>&1 | tee "$BUILD_LOG_DIR/01-main-build.log"
          STAGE_END=$(date +%s)
          echo ""
          echo "Build duration: $((STAGE_END - STAGE_START))s"

      - name: Quick smoke test (7 checks via build.sh)
        working-directory: ${{ env.PROJECT_DIR }}
        run: |
          echo ""
          echo "=== STEP: Quick smoke test ==="
          echo ""
          # The build.sh already runs quick_smoke_test after build, but we do extra verification here
          MAIN_IMAGE="devcontainer-base:${{ env.IMAGE_TAG }}"

          echo "--- Image size ---"
          docker images "$MAIN_IMAGE" --format "table {{.Repository}}\t{{.Tag}}\t{{.Size}}\t{{.CreatedAt}}"
          echo ""

          echo "--- Python 3.14.6 free-threading (cp314t) verification ---"
          docker run --rm "$MAIN_IMAGE" python --version
          docker run --rm "$MAIN_IMAGE" python -c "import sys; assert sys.version_info >= (3, 14), f'Python {sys.version} < 3.14'; print(f'✅ Python {sys.version.split()[0]} OK')"
          docker run --rm "$MAIN_IMAGE" python -c "
          import sys, sysconfig
          py_gil_disabled = sysconfig.get_config_var('Py_GIL_DISABLED')
          soabi = sysconfig.get_config_var('SOABI') or ''
          is_ft = (py_gil_disabled == 1) and ('cpython-314t' in soabi)
          gil_enabled = sys._is_gil_enabled()
          assert is_ft, f'Expected cp314t free-threading build, got Py_GIL_DISABLED={py_gil_disabled}, SOABI={soabi}'
          assert not gil_enabled, f'GIL should be disabled by default in cp314t, got _is_gil_enabled()={gil_enabled}'
          print(f'✅ Default Python is cp314t free-threading build (GIL disabled by default)')
          print(f'   SOABI: {soabi}')
          print(f'   GIL enabled: {gil_enabled}')
          print(f'   Use PYTHON_GIL=1 to enable GIL for C extension compatibility')
          "
          echo ""

          echo "--- libmamba solver verification ---"
          docker run --rm "$MAIN_IMAGE" conda config --show solver
          docker run --rm "$MAIN_IMAGE" python -c "import libmambapy; print(f'✅ libmambapy {libmambapy.__version__} OK')" 2>/dev/null || \
          docker run --rm "$MAIN_IMAGE" python -c "from libmambapy import __version__; print(f'✅ libmambapy OK')" 2>/dev/null || \
          echo "⚠️  libmambapy direct import failed (may be installed but import path differs)"
          echo ""

          echo "--- Conda verification ---"
          docker run --rm "$MAIN_IMAGE" conda --version
          docker run --rm "$MAIN_IMAGE" conda info --envs
          echo ""

          echo "--- JupyterLab verification ---"
          docker run --rm "$MAIN_IMAGE" jupyter lab --version 2>&1 | head -1
          echo ""

          echo "--- /opt/venv removed verification ---"
          if docker run --rm "$MAIN_IMAGE" test -d /opt/venv; then
            echo "❌ /opt/venv still exists!"
            exit 1
          else
            echo "✅ /opt/venv removed"
          fi
          echo ""

          echo "--- Core services verification ---"
          docker run --rm "$MAIN_IMAGE" tini --version 2>&1 | head -1
          docker run --rm "$MAIN_IMAGE" supervisord --version 2>&1 | head -1
          docker run --rm "$MAIN_IMAGE" docker --version
          echo ""

          echo "✅ Quick smoke test passed"

      - name: Deep verification (8 checks)
        working-directory: ${{ env.PROJECT_DIR }}
        run: |
          echo ""
          echo "=== STEP: Deep verification ==="
          echo ""
          MAIN_IMAGE="devcontainer-base:${{ env.IMAGE_TAG }}"

          echo "--- [1/8] Python build type detection (expecting cp314t, GIL disabled by default) ---"
          docker run --rm "$MAIN_IMAGE" python -c "
          import sys, sysconfig
          py_gil_disabled = sysconfig.get_config_var('Py_GIL_DISABLED')
          soabi = sysconfig.get_config_var('SOABI') or ''
          is_ft = (py_gil_disabled == 1) and ('cpython-314t' in soabi)
          gil_enabled = sys._is_gil_enabled()
          build_type = 'cp314t (free-threading, GIL disabled)' if is_ft else 'cp314 (standard, GIL always on)'
          print(f'  Python: {sys.version.split()[0]}')
          print(f'  Build:  {build_type}')
          print(f'  SOABI:  {soabi}')
          assert hasattr(sys, '_is_gil_enabled'), 'Python 3.14+ required'
          print(f'  GIL enabled: {gil_enabled}')
          assert is_ft, f'Expected default build to be cp314t free-threading, got {build_type}'
          assert not gil_enabled, f'GIL should be disabled by default in cp314t, got gil_enabled={gil_enabled}'
          print('  ✅ Python 3.14.6 cp314t free-threading confirmed (GIL disabled by default)')
          "
          echo ""

          echo "--- [1b/8] PYTHON_GIL=1 compatibility mode verification ---"
          docker run --rm -e PYTHON_GIL=1 "$MAIN_IMAGE" python -c "
          import sys, sysconfig
          py_gil_disabled = sysconfig.get_config_var('Py_GIL_DISABLED')
          gil_enabled = sys._is_gil_enabled()
          assert py_gil_disabled == 1, 'Still cp314t build'
          assert gil_enabled, f'PYTHON_GIL=1 should enable GIL, got gil_enabled={gil_enabled}'
          print(f'  ✅ PYTHON_GIL=1 enables GIL compatibility mode (GIL enabled: {gil_enabled})')
          "
          echo ""

          echo "--- [2/8] PEP 695 generic syntax ---"
          docker run --rm "$MAIN_IMAGE" python -c "
          type Point[T] = tuple[T, T]
          p: Point[int] = (1, 2)
          print('  ✅ PEP 695 generic type alias works')
          "
          echo ""

          echo "--- [3/8] pip install test ---"
          docker run --rm "$MAIN_IMAGE" pip install --no-cache-dir six 2>&1 | tail -3
          docker run --rm "$MAIN_IMAGE" python -c "import six; print(f'  ✅ pip install works (six {six.__version__})')"
          echo ""

          echo "--- [4/8] conda channels (conda-forge only) ---"
          docker run --rm "$MAIN_IMAGE" conda config --show channels
          channels=$(docker run --rm "$MAIN_IMAGE" conda config --show channels 2>&1 | grep -A10 "channels:" | grep -v "channels:" | tr -d ' -')
          if echo "$channels" | grep -q "defaults"; then
            echo "  ⚠️  defaults channel present"
          else
            echo "  ✅ conda-forge only (defaults removed)"
          fi
          echo ""

          echo "--- [5/8] Build metadata ---"
          docker run --rm "$MAIN_IMAGE" cat /etc/devcontainer-build-info
          echo ""

          echo "--- [6/8] entrypoint.sh syntax ---"
          docker run --rm "$MAIN_IMAGE" bash -n /entrypoint.sh && echo "  ✅ entrypoint.sh syntax OK"
          echo ""

          echo "--- [7/8] healthcheck.sh syntax ---"
          docker run --rm "$MAIN_IMAGE" bash -n /healthcheck.sh && echo "  ✅ healthcheck.sh syntax OK"
          echo ""

          echo "--- [8/8] Non-root user (devuser) ---"
          docker run --rm "$MAIN_IMAGE" su - devuser -c "python --version && conda --version && whoami"
          echo ""

          echo "✅ Deep verification (8/8) completed"

      - name: Run free-threading demo script (default cp314t)
        working-directory: ${{ env.PROJECT_DIR }}
        run: |
          echo ""
          echo "=== STEP: Free-threading demo (default cp314t, GIL disabled) ==="
          echo ""
          MAIN_IMAGE="devcontainer-base:${{ env.IMAGE_TAG }}"
          # Run demo on default Python (cp314t, GIL disabled by default)
          docker run --rm \
            -v "$(pwd)/examples:/examples:ro" \
            "$MAIN_IMAGE" python /examples/free_threading_demo.py 2>&1 | head -80
          echo ""
          echo "✅ Free-threading demo script runs correctly on default cp314t build"
          echo ""
          echo "=== STEP: Verify PYTHON_GIL=1 GIL compatibility mode ==="
          echo ""
          docker run --rm -e PYTHON_GIL=1 \
            -v "$(pwd)/examples:/examples:ro" \
            "$MAIN_IMAGE" python -c "
          import sys, sysconfig
          assert sysconfig.get_config_var('Py_GIL_DISABLED') == 1, 'cp314t build'
          assert sys._is_gil_enabled(), 'GIL should be enabled with PYTHON_GIL=1'
          print(f'  ✅ PYTHON_GIL=1 works: GIL enabled, full C extension compatibility')
          "
          echo ""
          echo "=== STEP: Verify standard cp314 build can be selected via build arg ==="
          echo ""
          echo "  (Standard cp314 build is available via --python-build cp314 at build time)"
          echo "  Build command example: ./scripts/build.sh --python-build cp314 --tag conda-libmamba-std"
          echo ""

      - name: Collect build logs
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: main-build-logs-${{ github.sha }}
          path: /tmp/build-logs/
          retention-days: 30
          if-no-files-found: ignore

      - name: Build summary
        if: always()
        run: |
          echo ""
          echo "╔══════════════════════════════════════════════════════════════╗"
          echo "║                 MAIN IMAGE BUILD SUMMARY                    ║"
          echo "╚══════════════════════════════════════════════════════════════╝"
          echo ""
          docker images devcontainer-base --format "table {{.Repository}}\t{{.Tag}}\t{{.Size}}\t{{.CreatedAt}}" 2>/dev/null || echo "No images found"
          echo ""
          if [ "${{ job.status }}" = "success" ]; then
            echo "  🎉 MAIN IMAGE BUILD AND TESTS PASSED"
          else
            echo "  ❌ JOB FAILED - check logs above"
          fi
          echo ""
          echo "End time: $(date -u '+%Y-%m-%d %H:%M:%S UTC')"

  # ──────────────────────────────────────────────────────────────────────
  # Stage 2: Build & Push (main branch only, when registry configured)
  # ──────────────────────────────────────────────────────────────────────
  push:
    name: Push to Registry
    runs-on: ubuntu-latest
    needs: build-main
    if: github.event_name != 'pull_request' && (github.event_name != 'workflow_dispatch' || github.event.inputs.push_registry == 'true')
    timeout-minutes: 30
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Print push configuration
        run: |
          echo "============================================================"
          echo "=== STAGE: Push to Registry                              ==="
          echo "============================================================"
          echo "Registry URL:       ${{ env.REGISTRY_URL }}"
          echo "Namespace:          ${{ env.REGISTRY_NAMESPACE }}"
          echo "Image tag:          ${{ env.IMAGE_TAG }}"
          echo "Username set:       ${{ secrets.REGISTRY_USERNAME != '' }}"
          echo "Password set:       ${{ secrets.REGISTRY_PASSWORD != '' }}"
          echo ""

      - name: Set up Docker Buildx
        run: |
          docker run --privileged --rm tonistiigi/binfmt --install all 2>&1 | tail -5 || true

      # ── Rebuild the image with Buildx (for multi-arch and push capability) ──
      - name: Login to Container Registry
        if: ${{ secrets.REGISTRY_USERNAME != '' && secrets.REGISTRY_PASSWORD != '' }}
        run: |
          echo ""
          echo "=== STEP: Logging in to ${{ env.REGISTRY_URL }} ==="
          echo "${{ secrets.REGISTRY_PASSWORD }}" | docker login "${{ env.REGISTRY_URL }}" \
            -u "${{ secrets.REGISTRY_USERNAME }}" --password-stdin
          echo "✅ Logged in to registry"

      - name: Build and push main image
        working-directory: ${{ env.PROJECT_DIR }}
        run: |
          echo ""
          echo "=== STEP: Building and pushing image ==="
          FULL_IMAGE="${{ env.REGISTRY_URL }}/${{ env.REGISTRY_NAMESPACE }}/devcontainer-base"
          TAGS=()

          # Determine tags
          if [ "${{ github.ref_type }}" = "branch" ] && [ "${{ github.ref_name }}" = "main" ]; then
            TAGS+=(--tag "${FULL_IMAGE}:conda-libmamba-ft")
            TAGS+=(--tag "${FULL_IMAGE}:conda-libmamba-ft-${{ env.IMAGE_TAG }}")
            TAGS+=(--tag "${FULL_IMAGE}:conda-libmamba-latest")
          elif [ "${{ github.event_name }}" = "schedule" ]; then
            TAGS+=(--tag "${FULL_IMAGE}:conda-libmamba-nightly")
            TAGS+=(--tag "${FULL_IMAGE}:conda-libmamba-$(date -u +%Y%m%d)")
          else
            TAGS+=(--tag "${FULL_IMAGE}:conda-libmamba-ft-${{ env.IMAGE_TAG }}")
          fi

          echo "Image: ${FULL_IMAGE}"
          for tag in "${TAGS[@]}"; do
            echo "  Tag: $tag"
          done
          echo ""

          # Build with Buildx and push
          docker buildx build \
            --push \
            --platform linux/amd64 \
            --build-arg APT_MIRROR=official \
            --build-arg PIP_MIRROR=official \
            --build-arg DOCKER_MIRROR=official \
            --build-arg CONDA_MIRROR=official \
            --build-arg PYTHON_VERSION=3.14.6 \
            --build-arg PYTHON_BUILD=cp314t \
            --build-arg BUILDKIT_INLINE_CACHE=1 \
            "${TAGS[@]}" \
            -t "${FULL_IMAGE}:${{ env.IMAGE_TAG }}" \
            .

          echo ""
          echo "✅ Image pushed successfully"
          echo ""
          echo "Pushed tags:"
          for tag in "${TAGS[@]}"; do
            echo "  $tag"
          done

      - name: Push summary
        if: always()
        run: |
          echo ""
          echo "============================================================"
          echo "=== PUSH STAGE COMPLETE: ${{ job.status }}                  ==="
          echo "============================================================"

  # ──────────────────────────────────────────────────────────────────────
  # Stage 3: Build Variants (experimental — Python 3.14 compat WIP)
  # ──────────────────────────────────────────────────────────────────────
  build-variants:
    name: Build Variants (Experimental)
    runs-on: ubuntu-latest
    needs: build-main
    if: github.event_name == 'schedule' || (github.event_name == 'workflow_dispatch' && github.event.inputs.build_variants == 'true')
    timeout-minutes: 120
    continue-on-error: true  # Variants are experimental until Python 3.14 compatibility verified
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Set up Docker Buildx
        run: docker run --privileged --rm tonistiigi/binfmt --install all 2>&1 | tail -5 || true

      - name: Rebuild main image for variants
        working-directory: ${{ env.PROJECT_DIR }}
        run: |
          echo "Rebuilding main image (Docker daemon-local for variant dependency chain)..."
          bash scripts/build.sh --tag ${{ env.IMAGE_TAG }} --apt-mirror official --pip-mirror official --conda-mirror official --no-quick-test

      - name: Build conda variant
        working-directory: ${{ env.PROJECT_DIR }}
        run: |
          echo ""
          echo "╔══════════════════════════════════════════════════════════════╗"
          echo "║  BUILD: Conda Variant (thin layer, mirror config)         ║"
          echo "╚══════════════════════════════════════════════════════════════╝"
          bash variants/build.sh --variant conda --tag ${{ env.IMAGE_TAG }}

      - name: Verify conda variant
        run: |
          echo ""
          echo "=== Verify conda variant ==="
          docker images "devcontainer-base:conda-${{ env.IMAGE_TAG }}" --format "table {{.Repository}}\t{{.Tag}}\t{{.Size}}"
          docker run --rm "devcontainer-base:conda-${{ env.IMAGE_TAG }}" conda --version
          docker run --rm "devcontainer-base:conda-${{ env.IMAGE_TAG }}" python --version
          echo "✅ Conda variant verified"

      - name: Build conda-llvm variant
        working-directory: ${{ env.PROJECT_DIR }}
        run: |
          echo ""
          echo "╔══════════════════════════════════════════════════════════════╗"
          echo "║  BUILD: Conda-LLVM Variant                                ║"
          echo "╚══════════════════════════════════════════════════════════════╝"
          bash variants/build.sh --variant conda-llvm --tag ${{ env.IMAGE_TAG }}

      - name: Build onnx-pytorch variant
        working-directory: ${{ env.PROJECT_DIR }}
        run: |
          echo ""
          echo "╔══════════════════════════════════════════════════════════════╗"
          echo "║  BUILD: ONNX-PyTorch Variant                              ║"
          echo "║  Note: PyTorch may not have Python 3.14 wheels yet         ║"
          echo "╚══════════════════════════════════════════════════════════════╝"
          bash variants/build.sh --variant onnx-pytorch --tag ${{ env.IMAGE_TAG }} || echo "⚠️  onnx-pytorch build failed (likely Python 3.14 compatibility)"

      - name: Build onnx-quantized variant
        working-directory: ${{ env.PROJECT_DIR }}
        run: |
          echo ""
          echo "╔══════════════════════════════════════════════════════════════╗"
          echo "║  BUILD: ONNX-Quantized Variant                            ║"
          echo "╚══════════════════════════════════════════════════════════════╝"
          bash variants/build.sh --variant onnx-quantized --tag ${{ env.IMAGE_TAG }} || echo "⚠️  onnx-quantized build failed (dependency on onnx-pytorch)"

      - name: Variants summary
        if: always()
        run: |
          echo ""
          docker images devcontainer-base --format "table {{.Repository}}\t{{.Tag}}\t{{.Size}}" 2>/dev/null
