#include "minishell.h"

static int has_slash(const char *s)
{
	return (s && strchr(s, '/'));
}

char *resolve_path(const char *cmd, t_shell *sh)
{
	char *path_env;
	char **parts;
	char *candidate;
	int i;

	if (!cmd)
		return NULL;
	if (is_builtin(cmd))
		return ms_strdup(cmd);
	if (has_slash(cmd))
		return ms_strdup(cmd);
	path_env = env_get(sh, "PATH");
	if (!path_env)
		return NULL;
	parts = ms_split(path_env, ':');
	if (!parts)
		return NULL;
	i = 0;
	while (parts[i])
	{
		candidate = ms_strjoin3(parts[i], "/", cmd);
		if (candidate && access(candidate, X_OK) == 0)
		{
			ms_free_split(parts);
			return candidate;
		}
		free(candidate);
		i++;
	}
	ms_free_split(parts);
	return NULL;
}
