using IdentityServer4.Models;
using Lada.Framework.Data.Domains.AI;
using Lada.Framework.Data.Enums;
using Lada.Framework.Data.Repositories;
using OpenAI;
using OpenAI.Chat;
using OpenAI.Models;


namespace Ladaer.BackEnd.Infrastructures.Services.AI
{
    public interface IOpenAiService
    {
        Task<string> CallPromptTemplateAsync(int templateId, string input);
    }

    public class OpenAiService : IOpenAiService
    {
        private readonly OpenAIClient _openAiClient;
        private readonly IRepository<AiCallLog> _aiCalllogRepository;
        private readonly IRepository<PromptTemplate> _promptTemplateRepository;

        public OpenAiService(OpenAIClient openAiClient, IRepository<AiCallLog> aiCalllogRepository, IRepository<PromptTemplate> promptTemplateRepository)
        {
            _openAiClient = openAiClient;
            _aiCalllogRepository = aiCalllogRepository;
            _promptTemplateRepository = promptTemplateRepository;
        }




        public async Task<string> CallPromptTemplateAsync(int templateId, string input)
        {
            var promptTemplate = await _promptTemplateRepository.GetByIdAsync(templateId);
            if (promptTemplate == null)
                throw new Exception($"Prompt ID {templateId} không tìm thấy.");

            string prompt = promptTemplate.Template.Replace("{{input}}", input);

            var log = new AiCallLog { Prompt = prompt };
            try
            {
                var chatRequest = new ChatRequest(
                    messages: new[] { new Message(Role.User, prompt) },
                    model: Model.ChatGPT4o,
                temperature: 0.7f
                );

                var chatResponse = await _openAiClient.ChatEndpoint.GetCompletionAsync(chatRequest);
                var responseText = chatResponse.FirstChoice.Message.Content.GetString();

                log.Response = responseText;
                log.Status = AiCallStatus.Success;
                await _aiCalllogRepository.InsertAsync(log);

                return responseText;
            }
            catch (Exception ex)
            {
                log.Status = AiCallStatus.Error;
                log.ErrorMessage = ex.Message;
                await _aiCalllogRepository.InsertAsync(log);
                throw;
            }
        }
    }
}
