name: Docker Build and Push

on:
  push:
    tags:
      - "v*"

jobs:
  docker:
    runs-on: amd64-ubuntu-24.04

    steps:
      - name: Clone repository
        run: |
          git clone "${{ gitea.server_url }}/${{ gitea.repository }}.git" .
          git checkout "${{ gitea.ref_name }}"

      - name: Set image metadata
        run: |
          IMAGE_NAME="$(echo "${{ gitea.repository }}" | tr '[:upper:]' '[:lower:]' | tr '_' '-')"
          IMAGE="${DOCKER_REGISTRY}/${DOCKER_USERNAME}/${IMAGE_NAME}:${{ gitea.ref_name }}"

          echo "IMAGE_NAME=${IMAGE_NAME}" >> "$GITEA_ENV"
          echo "IMAGE=${IMAGE}" >> "$GITEA_ENV"

      - name: Load and Validate Task Info
        run: |
          set -a
          . .gitea/workflows/task_info.env
          set +a

          for name in FRAMEWORK GPU_TYPE TASK_TYPE; do
            eval "value=\${${name}:-}"
            if [ "$name" = "FRAMEWORK" ] && [ -z "$value" ]; then
              echo "${name} is empty in .gitea/workflows/task_info.env"
              exit 1
            fi

            echo "${name}=${value}" >> "$GITEA_ENV"
          done

      - name: Validate Image Verify Metadata
        run: |
          if [ -z "${FIXED_TOKEN:-}" ]; then
            echo "FIXED_TOKEN is not configured on runner"
            exit 1
          fi

          if ! response="$(curl --silent --show-error --location --get 'https://modelhub.org.cn/adminApi/image-verify/validate' \
            --header "Xc-Token: ${FIXED_TOKEN}" \
            --data-urlencode "gpuType=${GPU_TYPE:-}" \
            --data-urlencode "taskType=${TASK_TYPE:-}")"; then
            echo "failed to call image verify validate API"
            exit 1
          fi

          VALIDATE_RESPONSE="$response" python3 - <<'PY'
          import json
          import os
          import sys

          raw = os.environ.get("VALIDATE_RESPONSE", "")
          try:
              body = json.loads(raw)
          except json.JSONDecodeError:
              print("image verify validate API returned invalid JSON")
              print(raw)
              sys.exit(1)

          if body.get("code") == 0 and body.get("data") is True:
              print("image verify metadata validation passed")
              sys.exit(0)

          message = body.get("message") or "unknown error"
          print(f"image verify metadata validation failed: {message}")
          print(raw)
          sys.exit(1)
          PY

      - name: Login to Docker Registry
        run: |
          echo "$DOCKER_PASSWORD" | docker login "$DOCKER_REGISTRY" \
            -u "$DOCKER_USERNAME" \
            --password-stdin

      - name: Build Docker Image
        run: |
          docker build -t "$IMAGE" .

      - name: Validate vLLM Package
        run: |
          docker run --rm --entrypoint python3 "$IMAGE" -c \
            "from vllm.benchmarks.lib.utils import write_to_json; print('vllm package ok')"

      - name: Push Docker Image
        run: |
          for attempt in 1 2 3; do
            echo "Starting docker push attempt ${attempt}/3 for ${IMAGE}"
            docker push "$IMAGE" &
            PUSH_PID=$!

            while kill -0 "$PUSH_PID" 2>/dev/null; do
              echo "docker push is still running at $(date -u '+%Y-%m-%dT%H:%M:%SZ')"
              sleep 60
            done

            if wait "$PUSH_PID"; then
              echo "docker push completed successfully"
              exit 0
            fi

            echo "docker push failed on attempt ${attempt}/3"
            sleep 30
          done

          echo "docker push failed after 3 attempts"
          exit 1

      - name: Notify Image Verify
        run: |
          if [ -z "${FIXED_TOKEN:-}" ]; then
            echo "FIXED_TOKEN is not configured on runner"
            exit 1
          fi

          curl --silent --show-error --fail-with-body --location --request POST 'https://modelhub.org.cn//adminApi/image-verify' \
            --header "Xc-Token: ${FIXED_TOKEN}" \
            --header 'Content-Type: application/json' \
            --data-raw "{
              \"framework\": \"${FRAMEWORK}\",
              \"gpuType\": \"${GPU_TYPE}\",
              \"imageUrl\": \"${IMAGE}\",
              \"taskType\": \"${TASK_TYPE}\",
              \"createBy\": \"${{ gitea.actor }}\",
              \"repoUrl\": \"${{ gitea.server_url }}/${{ gitea.repository }}\",
              \"tag\": \"${{ gitea.ref_name }}\"
            }"
