#!/bin/bash
# Build and Push Docker Images to Registry
# Usage: ./scripts/build-and-push-images.sh [registry] [version] [owner] [skip-existing]
# Example: ./scripts/build-and-push-images.sh gitea.harkon.co.uk v1.0.1 harkon
# Example (skip existing): ./scripts/build-and-push-images.sh gitea.harkon.co.uk v1.0.1 harkon skip

# Don't exit on error - we want to continue building other services
set +e

# Configuration
REGISTRY="${1:-gitea.harkon.co.uk}"
VERSION="${2:-latest}"
OWNER="${3:-harkon}"  # Gitea organization/team name
SKIP_EXISTING="${4:-}"  # Set to "skip" to skip already built images

# Note: Gitea container registry requires format: {registry}/{owner}/{image}:{tag}
# The owner must be your Gitea username or organization name

# Colors
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
NC='\033[0m'

log_info() {
    echo -e "${BLUE}ℹ️  $1${NC}"
}

log_success() {
    echo -e "${GREEN}✅ $1${NC}"
}

log_warning() {
    echo -e "${YELLOW}⚠️  $1${NC}"
}

# List of services to build
SERVICES=(
    "svc-ingestion"
    "svc-extract"
    "svc-kg"
    "svc-rag-retriever"
    "svc-rag-indexer"
    "svc-forms"
    "svc-hmrc"
    "svc-ocr"
    "svc-rpa"
    "svc-normalize-map"
    "svc-reason"
    "svc-firm-connectors"
    "svc-coverage"
    "ui-review"
)

# Check if Docker is running
if ! docker info > /dev/null 2>&1; then
    log_warning "Docker is not running. Please start Docker and try again."
    exit 1
fi

# Login to registry
log_info "Logging in to registry: $REGISTRY"
docker login $REGISTRY

# Build and push each service
for service in "${SERVICES[@]}"; do
    log_info "Building $service..."

    # Determine Dockerfile path
    if [ "$service" = "ui-review" ]; then
        DOCKERFILE="apps/ui_review/Dockerfile"
    else
        # Convert service name to directory name (e.g., svc-ingestion -> svc_ingestion)
        DIR_NAME=$(echo $service | tr '-' '_')
        DOCKERFILE="apps/$DIR_NAME/Dockerfile"
    fi

    # Check if Dockerfile exists
    if [ ! -f "$DOCKERFILE" ]; then
        log_warning "Dockerfile not found: $DOCKERFILE - Skipping $service"
        continue
    fi

    # Build image
    IMAGE_NAME="$REGISTRY/$OWNER/$service:$VERSION"

    # Check if image already exists locally (if skip mode enabled)
    if [ "$SKIP_EXISTING" = "skip" ]; then
        if docker images --format "{{.Repository}}:{{.Tag}}" | grep -q "^$IMAGE_NAME$"; then
            log_info "Image already exists: $IMAGE_NAME - Skipping build"

            # Still try to push it
            log_info "Pushing existing image: $IMAGE_NAME"
            if docker push $IMAGE_NAME 2>/dev/null; then
                log_success "Pushed: $IMAGE_NAME"
            else
                log_warning "Failed to push: $IMAGE_NAME (may already exist in registry)"
            fi

            # Also push latest tag
            if [ "$VERSION" != "latest" ]; then
                LATEST_IMAGE="$REGISTRY/$OWNER/$service:latest"
                if docker images --format "{{.Repository}}:{{.Tag}}" | grep -q "^$LATEST_IMAGE$"; then
                    docker push $LATEST_IMAGE 2>/dev/null
                fi
            fi

            echo ""
            continue
        fi
    fi

    log_info "Building: $IMAGE_NAME"

    if docker build \
        -t $IMAGE_NAME \
        -f $DOCKERFILE \
        --build-arg VERSION=$VERSION \
        --build-arg BUILD_DATE=$(date -u +'%Y-%m-%dT%H:%M:%SZ') \
        . ; then

        log_success "Built: $IMAGE_NAME"

        # Push image
        log_info "Pushing: $IMAGE_NAME"
        if docker push $IMAGE_NAME; then
            log_success "Pushed: $IMAGE_NAME"
        else
            log_warning "Failed to push: $IMAGE_NAME"
        fi

        # Also tag as version number if not latest
        if [ "$VERSION" != "latest" ]; then
            LATEST_IMAGE="$REGISTRY/$OWNER/$service:latest"
            docker tag $IMAGE_NAME $LATEST_IMAGE
            if docker push $LATEST_IMAGE; then
                log_success "Also pushed as: $LATEST_IMAGE"
            else
                log_warning "Failed to push: $LATEST_IMAGE"
            fi
        fi
    else
        log_warning "Failed to build: $IMAGE_NAME - Continuing with next service"
    fi

    echo ""
done

log_success "🎉 All images built and pushed successfully!"
log_info "Images pushed to: $REGISTRY/$OWNER"
log_info "Version: $VERSION"

# Show summary
echo ""
echo "Summary of pushed images:"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
for service in "${SERVICES[@]}"; do
    echo "  $REGISTRY/$OWNER/$service:$VERSION"
done
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
log_info "Next steps:"
echo "  1. Deploy to production: ./scripts/deploy-to-production.sh"
echo "  2. Or deploy specific step: ./scripts/deploy-to-production.sh services"
