#!/usr/bin/env bash
# compose.sh - Docker Compose operations

run_compose_up() {
    local service=$1
    local svc_dir="${REPO_PATH}/services/$service"
    local runtime_config_dir="${RUNTIME_PATH}/config/$service"

    if [[ ! -d "$svc_dir" ]]; then
        log "ERROR" "Service directory not found: $svc_dir"
        return 1
    fi

    mkdir -p "$runtime_config_dir"

    local compose_args=("-f" "${svc_dir}/docker-compose.yml")
    if [[ -f "${runtime_config_dir}/docker-compose.override.yml" ]]; then
        log "INFO" "Using override for $service"
        compose_args+=("-f" "${runtime_config_dir}/docker-compose.override.yml")
    fi

    # Determine .env
    local env_file=""
    if [[ -f "${runtime_config_dir}/.env" ]]; then
        env_file="${runtime_config_dir}/.env"
    elif [[ -f "${svc_dir}/.env" ]]; then
        env_file="${svc_dir}/.env"
    fi

    local run_cmd=("docker" "compose")
    run_cmd+=("${compose_args[@]}")
    if [[ -n "$env_file" ]]; then
        run_cmd+=("--env-file" "$env_file")
    fi
    run_cmd+=("up" "-d" "--remove-orphans")

    log "INFO" "Running: ${run_cmd[*]}"
    if ! "${run_cmd[@]}"; then
        log "ERROR" "Docker compose failed for $service"
        return 1
    fi
    return 0
}

export -f run_compose_up
