#!/bin/bash

# Build All Services Script for Bakery-IA
# This script builds and pushes all service images to the Gitea registry
# Used for first-time deployment when CI/CD pipeline isn't available yet

set -e

echo "=========================================="
echo "Bakery-IA Services Build Script"
echo "=========================================="
echo ""

# Check if we're in the correct directory
if [ ! -f "PRODUCTION_DEPLOYMENT_GUIDE.md" ]; then
    echo "Error: This script must be run from the root of the bakery-ia repository"
    exit 1
fi

# Get Gitea admin password
echo "Getting Gitea admin credentials..."
if ! GITEA_ADMIN_PASSWORD=$(kubectl get secret gitea-admin-secret -n gitea -o jsonpath='{.data.password}' | base64 -d 2>/dev/null); then
    echo "Error: Could not get Gitea admin password"
    echo "Make sure you've completed Phase 5 (CI/CD Infrastructure) first"
    exit 1
fi

# Login to Gitea registry (use external HTTPS URL)
echo "Logging in to Gitea registry..."
docker login registry.bakewise.ai -u bakery-admin -p "$GITEA_ADMIN_PASSWORD"

# Define the registry URL (use external HTTPS URL - containerd requires HTTPS for auth)
REGISTRY="registry.bakewise.ai/bakery-admin"

# Define all services to build
# Format: "directory_name:image_name"
# Note: directory names use underscores (e.g., alert_processor), image names use hyphens (e.g., alert-processor)
SERVICES=(
    "gateway:gateway"
    "frontend:dashboard"
    "auth:auth-service"
    "tenant:tenant-service"
    "training:training-service"
    "forecasting:forecasting-service"
    "sales:sales-service"
    "external:external-service"
    "notification:notification-service"
    "inventory:inventory-service"
    "recipes:recipes-service"
    "suppliers:suppliers-service"
    "pos:pos-service"
    "orders:orders-service"
    "production:production-service"
    "procurement:procurement-service"
    "distribution:distribution-service"
    "orchestrator:orchestrator-service"
    "alert_processor:alert-processor"
    "ai_insights:ai-insights-service"
    "demo_session:demo-session-service"
)

# Build each service
echo ""
echo "Starting build process..."
echo "This may take 15-30 minutes depending on your system."
echo ""

FAILED_SERVICES=()
SUCCESS_COUNT=0

for service_def in "${SERVICES[@]}"; do
    IFS=':' read -r service_name image_name <<< "$service_def"

    echo "=========================================="
    echo "Building: $service_name -> $image_name"
    echo "=========================================="

    if [ "$service_name" = "gateway" ]; then
        # Gateway service
        docker build -t "$REGISTRY/$image_name:latest" \
            --build-arg BASE_REGISTRY="$REGISTRY" \
            --build-arg PYTHON_IMAGE="python:3.11-slim" \
            -f "gateway/Dockerfile" .
    elif [ "$service_name" = "frontend" ]; then
        # Frontend service (uses node:18-alpine and nginx:1.25-alpine internally)
        docker build -t "$REGISTRY/$image_name:latest" \
            -f "frontend/Dockerfile.kubernetes" frontend/
    else
        # Microservices (in services/ directory)
        docker build -t "$REGISTRY/$image_name:latest" \
            --build-arg BASE_REGISTRY="$REGISTRY" \
            --build-arg PYTHON_IMAGE="python:3.11-slim" \
            -f "services/$service_name/Dockerfile" .
    fi
    
    # Push the image
    echo "Pushing $image_name to registry..."
    if docker push "$REGISTRY/$image_name:latest"; then
        echo "✅ Successfully built and pushed $image_name"
        SUCCESS_COUNT=$((SUCCESS_COUNT + 1))
    else
        echo "❌ Failed to push $image_name"
        FAILED_SERVICES+=("$image_name")
    fi
    
    echo ""
done

echo "=========================================="
echo "Build Summary"
echo "=========================================="
echo "Total services: ${#SERVICES[@]}"
echo "Successfully built and pushed: $SUCCESS_COUNT"

if [ ${#FAILED_SERVICES[@]} -gt 0 ]; then
    echo "Failed services: ${#FAILED_SERVICES[@]}"
    echo "Failed list: ${FAILED_SERVICES[*]}"
    echo ""
    echo "⚠️  Some services failed to build/push"
    exit 1
else
    echo "✅ All services built and pushed successfully!"
    echo ""
    echo "You can now proceed to Phase 6: Deploy Application Services"
    echo "Run: kubectl apply -k infrastructure/environments/prod/k8s-manifests"
fi