#!/bin/bash
# Kubernetes Service Group Definitions
# File: service-groups.sh

# Service group definitions
declare -A SERVICE_GROUPS

# Infrastructure services (Redis, MinIO, Static Files)
SERVICE_GROUPS[infrastructure]="redis minio static-files-access static-files"

# Application services (all EveAI apps)
SERVICE_GROUPS[apps]="eveai-app eveai-api eveai-chat-client eveai-workers eveai-chat-workers eveai-beat eveai-entitlements"


# Monitoring services
SERVICE_GROUPS[monitoring]="prometheus grafana flower"

# All services combined
SERVICE_GROUPS[all]="redis minio static-files-access static-files eveai-app eveai-api eveai-chat-client eveai-workers eveai-chat-workers eveai-beat eveai-entitlements prometheus grafana flower"

# Service to YAML file mapping
declare -A SERVICE_YAML_FILES

# Infrastructure services
SERVICE_YAML_FILES[redis]="redis-minio-services.yaml"
SERVICE_YAML_FILES[minio]="redis-minio-services.yaml"
SERVICE_YAML_FILES[static-files-access]="static-files-access.yaml"

# Application services
SERVICE_YAML_FILES[eveai-app]="eveai-services.yaml"
SERVICE_YAML_FILES[eveai-api]="eveai-services.yaml"
SERVICE_YAML_FILES[eveai-chat-client]="eveai-services.yaml"
SERVICE_YAML_FILES[eveai-workers]="eveai-services.yaml"
SERVICE_YAML_FILES[eveai-chat-workers]="eveai-services.yaml"
SERVICE_YAML_FILES[eveai-beat]="eveai-services.yaml"
SERVICE_YAML_FILES[eveai-entitlements]="eveai-services.yaml"

# Static files service
SERVICE_YAML_FILES[static-files]="static-files-service.yaml"

# Monitoring services
SERVICE_YAML_FILES[prometheus]="monitoring-services.yaml"
SERVICE_YAML_FILES[grafana]="monitoring-services.yaml"
SERVICE_YAML_FILES[flower]="monitoring-services.yaml"

# Service deployment order (for dependencies)
declare -A SERVICE_DEPLOY_ORDER

# Infrastructure first (order 1)
SERVICE_DEPLOY_ORDER[redis]=1
SERVICE_DEPLOY_ORDER[minio]=1
SERVICE_DEPLOY_ORDER[static-files-access]=1
SERVICE_DEPLOY_ORDER[static-files]=1

# Core apps next (order 2)
SERVICE_DEPLOY_ORDER[eveai-app]=2
SERVICE_DEPLOY_ORDER[eveai-api]=2
SERVICE_DEPLOY_ORDER[eveai-chat-client]=2
SERVICE_DEPLOY_ORDER[eveai-entitlements]=2

# Workers after core apps (order 3)
SERVICE_DEPLOY_ORDER[eveai-workers]=3
SERVICE_DEPLOY_ORDER[eveai-chat-workers]=3
SERVICE_DEPLOY_ORDER[eveai-beat]=3


# Monitoring last (order 5)
SERVICE_DEPLOY_ORDER[prometheus]=5
SERVICE_DEPLOY_ORDER[grafana]=5
SERVICE_DEPLOY_ORDER[flower]=5

# Service health check endpoints
declare -A SERVICE_HEALTH_ENDPOINTS

SERVICE_HEALTH_ENDPOINTS[eveai-app]="/healthz/ready:5001"
SERVICE_HEALTH_ENDPOINTS[eveai-api]="/healthz/ready:5003"
SERVICE_HEALTH_ENDPOINTS[eveai-chat-client]="/healthz/ready:5004"
SERVICE_HEALTH_ENDPOINTS[redis]="ping"
SERVICE_HEALTH_ENDPOINTS[minio]="ready"

# Get services in a group
get_services_in_group() {
    local group=$1
    if [[ -n "${SERVICE_GROUPS[$group]}" ]]; then
        echo "${SERVICE_GROUPS[$group]}"
    else
        log_operation "ERROR" "Unknown service group: $group"
        local available_groups=("${!SERVICE_GROUPS[@]}")
        echo "Available groups: ${available_groups[*]}"
        return 1
    fi
}

# Get YAML file for a service
get_yaml_file_for_service() {
    local service=$1
    if [[ -n "${SERVICE_YAML_FILES[$service]}" ]]; then
        echo "${SERVICE_YAML_FILES[$service]}"
    else
        log_operation "ERROR" "No YAML file defined for service: $service"
        return 1
    fi
}

# Get deployment order for a service
get_service_deploy_order() {
    local service=$1
    echo "${SERVICE_DEPLOY_ORDER[$service]:-999}"
}

# Get health check endpoint for a service
get_service_health_endpoint() {
    local service=$1
    echo "${SERVICE_HEALTH_ENDPOINTS[$service]:-}"
}

# Sort services by deployment order
sort_services_by_deploy_order() {
    local services=("$@")
    local sorted_services=()
    
    # Create array of service:order pairs
    local service_orders=()
    for service in "${services[@]}"; do
        local order=$(get_service_deploy_order "$service")
        service_orders+=("$order:$service")
    done
    
    # Sort by order and extract service names
    IFS=$'\n' sorted_services=($(printf '%s\n' "${service_orders[@]}" | sort -n | cut -d: -f2))
    echo "${sorted_services[@]}"
}

# Get services that should be deployed before a given service
get_service_dependencies() {
    local target_service=$1
    local target_order=$(get_service_deploy_order "$target_service")
    local dependencies=()
    
    # Find all services with lower deployment order
    for service in "${!SERVICE_DEPLOY_ORDER[@]}"; do
        local service_order="${SERVICE_DEPLOY_ORDER[$service]}"
        if [[ "$service_order" -lt "$target_order" ]]; then
            dependencies+=("$service")
        fi
    done
    
    echo "${dependencies[@]}"
}

# Check if a service belongs to a group
is_service_in_group() {
    local service=$1
    local group=$2
    local group_services="${SERVICE_GROUPS[$group]}"
    
    if [[ " $group_services " =~ " $service " ]]; then
        return 0
    else
        return 1
    fi
}

# Get all unique YAML files for a group
get_yaml_files_for_group() {
    local group=$1
    local services
    services=$(get_services_in_group "$group")
    
    if [[ $? -ne 0 ]]; then
        return 1
    fi
    
    local yaml_files=()
    local unique_files=()
    
    for service in $services; do
        local yaml_file=$(get_yaml_file_for_service "$service")
        if [[ -n "$yaml_file" ]]; then
            yaml_files+=("$yaml_file")
        fi
    done
    
    # Remove duplicates
    IFS=$'\n' unique_files=($(printf '%s\n' "${yaml_files[@]}" | sort -u))
    echo "${unique_files[@]}"
}

# Display service group information
show_service_groups() {
    echo "📋 Available Service Groups:"
    echo "============================"
    
    for group in "${!SERVICE_GROUPS[@]}"; do
        echo ""
        echo "🔹 $group:"
        local services="${SERVICE_GROUPS[$group]}"
        for service in $services; do
            local order=$(get_service_deploy_order "$service")
            local yaml_file=$(get_yaml_file_for_service "$service")
            echo "   • $service (order: $order, file: $yaml_file)"
        done
    done
}

# Validate service group configuration
validate_service_groups() {
    local errors=0
    
    echo "🔍 Validating service group configuration..."
    
    # Check if all services have YAML files defined
    for group in "${!SERVICE_GROUPS[@]}"; do
        local services="${SERVICE_GROUPS[$group]}"
        for service in $services; do
            if [[ -z "${SERVICE_YAML_FILES[$service]}" ]]; then
                log_operation "ERROR" "Service '$service' in group '$group' has no YAML file defined"
                ((errors++))
            fi
        done
    done
    
    # Check if YAML files exist
    if [[ -n "$K8S_CONFIG_DIR" ]]; then
        for yaml_file in "${SERVICE_YAML_FILES[@]}"; do
            if [[ ! -f "$K8S_CONFIG_DIR/$yaml_file" ]]; then
                log_operation "WARNING" "YAML file '$yaml_file' not found in $K8S_CONFIG_DIR"
            fi
        done
    fi
    
    if [[ $errors -eq 0 ]]; then
        log_operation "SUCCESS" "Service group configuration is valid"
        return 0
    else
        log_operation "ERROR" "Found $errors configuration errors"
        return 1
    fi
}

# Export functions for use in other scripts
if [[ -n "$ZSH_VERSION" ]]; then
    typeset -f get_services_in_group get_yaml_file_for_service get_service_deploy_order > /dev/null
    typeset -f get_service_health_endpoint sort_services_by_deploy_order get_service_dependencies > /dev/null
    typeset -f is_service_in_group get_yaml_files_for_group show_service_groups validate_service_groups > /dev/null
else
    export -f get_services_in_group get_yaml_file_for_service get_service_deploy_order
    export -f get_service_health_endpoint sort_services_by_deploy_order get_service_dependencies
    export -f is_service_in_group get_yaml_files_for_group show_service_groups validate_service_groups
fi