/* ft_printf.c */

#include "pf_private_header.h"
#include "libft.h"

/*
** -printf receive a string to print with a variadic number of arguments
** -it will go in a loop through each 'words'
** -a word is either a string containing no '%' or a conversion starting by '%'
** -if it's a string it's printed right away
** -if it's a conversion it will call pf_convert_with_flags for some actions :
** -1 expand the specifier according to its type and its length
**    and put in a string 'print'
** -2 transform 'print' according to the flags
*/
int ft_printf(const char *string, ...)
{
	va_list ap;
	int ret;

	va_start(ap, string);
	ret = ft_vdprintf(STDOUT_FILENO, string, ap);
	va_end(ap);
	return (ret);
}

/*
** ft_dprintf : prints formatted output to a file descriptor
** @param fd    : the file descriptor to write to (e.g., STDOUT_FILENO, STDERR_FILENO)
** @param string: the format string (see ft_printf for format specifiers)
** @param ...   : variadic arguments for the format string
** @return      : the number of characters printed, or -1 on error
** @note        : this is the file descriptor equivalent of ft_printf.
**               Use this when you need to print to a specific file descriptor,
**               such as STDERR_FILENO or a custom file descriptor from open().
*/
int ft_dprintf(int fd, const char *string, ...)
{
	va_list ap;
	int ret;

	va_start(ap, string);
	ret = ft_vdprintf(fd, string, ap);
	va_end(ap);
	return (ret);
}

/*
** ft_vdprintf : core implementation of formatted output to a file descriptor
** @param fd     : the file descriptor to write to
** @param string : the format string (see ft_printf for format specifiers)
** @param ap     : va_list containing the variadic arguments for the format string
** @return       : the number of characters printed, or -1 on error
** @note         : this is the va_list version of ft_dprintf.
**               It processes the format string and variadic arguments,
**               then writes the result to the file descriptor `fd`.
**               This function is used internally by ft_dprintf and ft_printf.
*/
int ft_vdprintf(int fd, const char *string, va_list ap)
{
	char *s;
	char *type;
	int length;
	int size;

	length = 0;
	while ((s = pf_next_word(&string)) != NULL)
	{
		if ((type = pf_specifier(s)) == NULL)
			length += pf_put_word(fd, s, type, ft_strlen(s));
		else
		{
			size = 0;
			if (!(s = pf_convert_with_flags(s, ap, type, &size)))
				return (-1);
			length += pf_put_word(fd, s, type, size);
		}
	}
	free(s);
	return (length);
}
