substitutions:
  _IMAGE_NAME: 'development'
  _ARTIFACT_REGISTRY_REPO: 'us-docker.pkg.dev/gemini-code-dev/gemini-cli'

steps:
  # Step 1: Install root dependencies
  - name: 'us-west1-docker.pkg.dev/gemini-code-dev/gemini-code-containers/gemini-code-builder'
    id: 'Install Dependencies'
    entrypoint: 'npm'
    args: ['install']

  # Step 2: Authenticate for Docker
  - name: 'us-west1-docker.pkg.dev/gemini-code-dev/gemini-code-containers/gemini-code-builder'
    id: 'Authenticate docker'
    entrypoint: 'npm'
    args: ['run', 'auth']

  # Step 3: Build workspace packages
  - name: 'us-west1-docker.pkg.dev/gemini-code-dev/gemini-code-containers/gemini-code-builder'
    id: 'Build packages'
    entrypoint: 'npm'
    args: ['run', 'build:packages']

  # Step 4: Build Development Image
  - name: 'us-west1-docker.pkg.dev/gemini-code-dev/gemini-code-containers/gemini-code-builder'
    id: 'Build Development Image'
    entrypoint: 'bash'
    env:
      - 'RAW_BRANCH_VALUE=${BRANCH_NAME}'
    args:
      - '-c'
      - |-
        IMAGE_BASE="${_ARTIFACT_REGISTRY_REPO}/${_IMAGE_NAME}"

        # Determine the primary tag (branch name or 'latest' for main)
        # Use $$ for shell variables to avoid Cloud Build attempting premature substitution
        RAW_BRANCH="$$RAW_BRANCH_VALUE"
        if [ "$${RAW_BRANCH}" == "main" ]; then
          TAG_PRIMARY="latest"
        else
          TAG_PRIMARY=$$(echo "$${RAW_BRANCH}" | sed 's/[^a-zA-Z0-9]/-/g' | tr '[:upper:]' '[:lower:]')
        fi

        # Use SHORT_SHA if available (Cloud Build) or fallback to latest-dev
        TAG_SHA="$${SHORT_SHA:-latest-dev}"

        echo "📦 Building Development Image for: $${RAW_BRANCH} -> $${TAG_PRIMARY} ($${TAG_SHA})"

        docker build -f .gcp/Dockerfile.development \
          -t "$${IMAGE_BASE}:$${TAG_SHA}" \
          -t "$${IMAGE_BASE}:$${TAG_PRIMARY}" .

        docker push "$${IMAGE_BASE}:$${TAG_SHA}"
        docker push "$${IMAGE_BASE}:$${TAG_PRIMARY}"

options:
  defaultLogsBucketBehavior: 'REGIONAL_USER_OWNED_BUCKET'
  dynamicSubstitutions: true
