#!/bin/bash
# GitDataAI Docker Build Script

set -e

# Get version from Cargo.toml
PROJECT_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
CARGO_VERSION=$(grep -m1 'version' "${PROJECT_ROOT}/Cargo.toml" | sed 's/.*"\(.*\)".*/\1/')

# Configuration
REGISTRY=${REGISTRY:-""}
TAG=${TAG:-"${CARGO_VERSION:-latest}"}
PLATFORM=${PLATFORM:-"linux/amd64"}

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

# Services to build
SERVICES=("gitdata" "email" "gitpod" "gitsync" "migrate" "web")

# Function to print colored output
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Function to build a service
build_service() {
    local service=$1
    local dockerfile="${PROJECT_ROOT}/docker/${service}.Dockerfile"
    local image_name="gitdata-${service}"

    # Add registry prefix if set
    if [ -n "$REGISTRY" ]; then
        image_name="${REGISTRY}/${image_name}"
    fi

    log_info "Building ${service}..."

    if [ ! -f "$dockerfile" ]; then
        log_error "Dockerfile not found: ${dockerfile}"
        return 1
    fi

    docker build \
        -f "$dockerfile" \
        -t "${image_name}:${TAG}" \
        --platform "$PLATFORM" \
        "$PROJECT_ROOT"

    log_info "Successfully built ${image_name}:${TAG}"
}

# Parse command line arguments
BUILD_SERVICES=()
BUILD_ALL=true

while [[ $# -gt 0 ]]; do
    case $1 in
        --tag|-t)
            TAG="$2"
            shift 2
            ;;
        --registry|-r)
            REGISTRY="$2"
            shift 2
            ;;
        --platform|-p)
            PLATFORM="$2"
            shift 2
            ;;
        --help|-h)
            echo "Usage: $0 [OPTIONS] [SERVICE...]"
            echo ""
            echo "Options:"
            echo "  -t, --tag TAG        Docker image tag (default: latest)"
            echo "  -r, --registry REG   Docker registry prefix"
            echo "  -p, --platform PLAT  Target platform (default: linux/amd64)"
            echo "  -h, --help           Show this help message"
            echo ""
            echo "Services:"
            echo "  gitdata              Main API service"
            echo "  email                Email service"
            echo "  gitpod               GitPod service"
            echo "  gitsync              GitSync service"
            echo "  migrate              Database migration"
            echo "  web                  Web frontend"
            echo ""
            echo "Examples:"
            echo "  $0                              # Build all services"
            echo "  $0 gitdata web                  # Build specific services"
            echo "  $0 -t v1.0.0 -r registry.com   # Build with custom tag and registry"
            exit 0
            ;;
        *)
            BUILD_SERVICES+=("$1")
            BUILD_ALL=false
            shift
            ;;
    esac
done

# Build services
log_info "Starting Docker build..."
log_info "Registry: ${REGISTRY:-none}"
log_info "Tag: ${TAG}"
log_info "Platform: ${PLATFORM}"

if [ "$BUILD_ALL" = true ]; then
    log_info "Building all services..."
    for service in "${SERVICES[@]}"; do
        build_service "$service"
    done
else
    log_info "Building specified services: ${BUILD_SERVICES[*]}"
    for service in "${BUILD_SERVICES[@]}"; do
        build_service "$service"
    done
fi

log_info "Build completed successfully!"