#!/bin/bash

# Docker Build Script for Developer Portfolio Tracker
# This script builds all Docker images for the microservices

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Configuration
REGISTRY=${DOCKER_REGISTRY:-"localhost:5000"}
TAG=${DOCKER_TAG:-"latest"}
BUILD_ARGS=${DOCKER_BUILD_ARGS:-""}

# Services to build
SERVICES=(
    "user-service"
    "task-service"
    "analytics-service"
    "diagram-service"
    "api-gateway"
    "frontend"
)

echo -e "${GREEN}Starting Docker build process...${NC}"
echo -e "${YELLOW}Registry: ${REGISTRY}${NC}"
echo -e "${YELLOW}Tag: ${TAG}${NC}"

# Function to build a service
build_service() {
    local service=$1
    local dockerfile="packages/${service}/Dockerfile"
    local image_name="${REGISTRY}/portfolio-${service}:${TAG}"
    
    echo -e "${YELLOW}Building ${service}...${NC}"
    
    if [ ! -f "$dockerfile" ]; then
        echo -e "${RED}Error: Dockerfile not found at ${dockerfile}${NC}"
        return 1
    fi
    
    # Build the image
    docker build \
        -f "$dockerfile" \
        -t "$image_name" \
        ${BUILD_ARGS} \
        .
    
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}✓ Successfully built ${service}${NC}"
        
        # Also tag as latest if not already latest
        if [ "$TAG" != "latest" ]; then
            docker tag "$image_name" "${REGISTRY}/portfolio-${service}:latest"
        fi
    else
        echo -e "${RED}✗ Failed to build ${service}${NC}"
        return 1
    fi
}

# Function to build all services
build_all() {
    local failed_services=()
    
    for service in "${SERVICES[@]}"; do
        if ! build_service "$service"; then
            failed_services+=("$service")
        fi
    done
    
    if [ ${#failed_services[@]} -eq 0 ]; then
        echo -e "${GREEN}✓ All services built successfully!${NC}"
        return 0
    else
        echo -e "${RED}✗ Failed to build the following services:${NC}"
        for service in "${failed_services[@]}"; do
            echo -e "${RED}  - ${service}${NC}"
        done
        return 1
    fi
}

# Function to push images to registry
push_images() {
    echo -e "${YELLOW}Pushing images to registry...${NC}"
    
    for service in "${SERVICES[@]}"; do
        local image_name="${REGISTRY}/portfolio-${service}:${TAG}"
        echo -e "${YELLOW}Pushing ${image_name}...${NC}"
        
        docker push "$image_name"
        
        if [ $? -eq 0 ]; then
            echo -e "${GREEN}✓ Successfully pushed ${service}${NC}"
        else
            echo -e "${RED}✗ Failed to push ${service}${NC}"
        fi
    done
}

# Function to show image sizes
show_image_sizes() {
    echo -e "${YELLOW}Image sizes:${NC}"
    for service in "${SERVICES[@]}"; do
        local image_name="${REGISTRY}/portfolio-${service}:${TAG}"
        local size=$(docker images --format "table {{.Size}}" "$image_name" | tail -n 1)
        echo -e "${GREEN}  ${service}: ${size}${NC}"
    done
}

# Function to clean up dangling images
cleanup() {
    echo -e "${YELLOW}Cleaning up dangling images...${NC}"
    docker image prune -f
    echo -e "${GREEN}✓ Cleanup completed${NC}"
}

# Main execution
case "${1:-build}" in
    "build")
        build_all
        show_image_sizes
        ;;
    "push")
        push_images
        ;;
    "build-push")
        build_all && push_images
        show_image_sizes
        ;;
    "cleanup")
        cleanup
        ;;
    "help")
        echo "Usage: $0 [build|push|build-push|cleanup|help]"
        echo ""
        echo "Commands:"
        echo "  build       Build all Docker images (default)"
        echo "  push        Push all images to registry"
        echo "  build-push  Build and push all images"
        echo "  cleanup     Remove dangling images"
        echo "  help        Show this help message"
        echo ""
        echo "Environment variables:"
        echo "  DOCKER_REGISTRY  Docker registry URL (default: localhost:5000)"
        echo "  DOCKER_TAG       Image tag (default: latest)"
        echo "  DOCKER_BUILD_ARGS Additional build arguments"
        ;;
    *)
        echo -e "${RED}Unknown command: $1${NC}"
        echo "Use '$0 help' for usage information"
        exit 1
        ;;
esac