using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.ChatCompletion;
using Microsoft.SemanticKernel.Connectors.AzureOpenAI;
using Microsoft.SemanticKernel.Connectors.OpenAI;
using Volo.Abp.DependencyInjection;
using Yi.Framework.ChatHub.Domain.Shared.Dtos;

namespace Yi.Framework.ChatHub.Domain.Managers
{
    public class AiManager : ISingletonDependency
    {
        private readonly Kernel _client;

        public AiManager(Kernel client)
        {
            _client = client;
        }

        public async IAsyncEnumerable<string?> ChatAsStreamAsync(string model, List<AiChatContextDto> aiChatContextDtos)
        {
            if (aiChatContextDtos.Count == 0)
            {
                yield return null;
            }

            
            var openSettings = new AzureOpenAIPromptExecutionSettings()
            {
                MaxTokens = 3000
            };

            var chatCompletionService = this._client.GetRequiredService<IChatCompletionService>(model);

            var history = new ChatHistory();
            foreach (var aiChatContextDto in aiChatContextDtos)
            {
                if (aiChatContextDto.AnswererType == AnswererTypeEnum.Ai)
                {
                    history.AddAssistantMessage(aiChatContextDto.Message);
                }
                else if (aiChatContextDto.AnswererType == AnswererTypeEnum.User)
                {
                    history.AddUserMessage(aiChatContextDto.Message);
                }
            }

            var results = chatCompletionService.GetStreamingChatMessageContentsAsync(
                chatHistory: history,
                executionSettings: openSettings,
                kernel: _client);
            
            await foreach (var result in results)
            {
                yield return result?.Content;
            }
        }
    }
}