using API.DBAccess;
using API.Models.RecipeModels;
using OpenAI.Chat;

namespace API.Services
{
    public class OpenAiRecipes
    {
        private readonly IConfiguration _configuration;

        public OpenAiRecipes(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        public async Task<ChatCompletion> ChatGPT(GenerateRecipeDTO recipeDTO)
        {
            ChatClient client = new(
                model: _configuration["OpenAI:Model"],
                apiKey: _configuration["OpenAI:APIKey"]
                );

            string allergi = "";

            if (recipeDTO.Allergi.Count != 0)
            {
                foreach (var item in recipeDTO.Allergi)
                {
                    allergi += item + ", ";
                }
            }
            else
            {
                allergi = "none";
            }

            string jsonStructure = "{ name: string, description: string,  directions: [string, string, ...], ingredients: [ { amount: number?, unit: string?, name: string }]}";

            // The messages for chat gpt
            List<ChatMessage> messages = [
                new SystemChatMessage($"You are a a helpful assistant. You give back {recipeDTO.NumberOfRecipes} recipes on the dish that you have been given. " +
                $"Answer in the language {recipeDTO.Language}. " +
                $"Answer in .json format using this structure {jsonStructure}. " +
                $"For the ingredients keep the names short ie. 'grated cheese' instead of 'cheese, grated (e.g., cheddar or gouda)'" +
                $"Avoid item/dishes that the person is allergic to here is a list {allergi}"),
                new UserChatMessage(recipeDTO.Dish),
                ];

            // Here we send the mess messages to chatgpt
            ChatCompletion chat = await client.CompleteChatAsync(messages);

            return chat;
        }
    }
}