#!/bin/bash
set -e

# Configuration
AWS_REGION="${AWS_REGION:-ap-south-1}"
AWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
ECR_REPOSITORY="qdrant-cluster"
IMAGE_TAG="${1:-latest}"

ECR_URI="${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com/${ECR_REPOSITORY}"

echo "🔨 Building Qdrant cluster image..."
echo "   Repository: ${ECR_REPOSITORY}"
echo "   Tag: ${IMAGE_TAG}"
echo "   ECR URI: ${ECR_URI}:${IMAGE_TAG}"

# Navigate to docker directory
cd "$(dirname "$0")"

# Build the image for ARM64 (Fargate ARM)
echo "📦 Building Docker image for ARM64..."
docker buildx build --platform linux/arm64 \
    -t "${ECR_REPOSITORY}:${IMAGE_TAG}" \
    -t "${ECR_URI}:${IMAGE_TAG}" \
    -f Dockerfile.qdrant \
    .

# Login to ECR
echo "🔐 Logging into ECR..."
aws ecr get-login-password --region "${AWS_REGION}" | \
    docker login --username AWS --password-stdin "${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com"

# Create ECR repository if it doesn't exist
echo "📋 Ensuring ECR repository exists..."
aws ecr describe-repositories --repository-names "${ECR_REPOSITORY}" --region "${AWS_REGION}" 2>/dev/null || \
    aws ecr create-repository --repository-name "${ECR_REPOSITORY}" --region "${AWS_REGION}"

# Push to ECR
echo "⬆️  Pushing image to ECR..."
docker push "${ECR_URI}:${IMAGE_TAG}"

echo "✅ Image pushed successfully!"
echo "   ECR URI: ${ECR_URI}:${IMAGE_TAG}"
echo ""
echo "To use this image in CloudFormation, update the QdrantImageTag parameter or change the Image URL to:"
echo "   ${ECR_URI}:${IMAGE_TAG}"
