using AIAss.Protos;
using Grpc.Core;
using Hushian.Application.Contracts;
using Hushian.Application.Models;
using Hushian.Application.Models.aia;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace Hushian.Infrastructure.Ai_Ass
{
    public class openAI : Iaiass
    {
        const string model = "gpt-4o-mini";
        private aigrpcserver _aigrpc;
        private aiSetting _aiSettings;
        public openAI(IOptions<aigrpcserver> aigrpc, IOptions<aiSetting> aiSettings)
        {
            _aigrpc = aigrpc.Value;
            _aiSettings = aiSettings.Value;
        }

        public async Task<ResponseBase<string>> SendQuestion(aiRequestModel Request)
        {
            var Response = new ResponseBase<string>();
            var channel = new Channel(_aigrpc.target, ChannelCredentials.Insecure);

            try
            {
                await channel.ConnectAsync();
                
                var aiaServiceClient = new aiAssistance.aiAssistanceClient(channel);
               var response= await aiaServiceClient.SendQuestionAsync
                    (new aiaRequest() 
                    { Prompts = Request.ToString(),
                        Question = Request.question,
                        Model=model});

                if (response!=null)
                {
                    Response.Value = response.Message;
                    Response.Success = true;
                }
                else
                {
                    Response.Errors.Add("خطا در ارتباط سرور ai");
                }
            }
            catch (Exception ex)
            {
                Response.Errors.Add("خطا مدیریت نشده در ارتباط سرور ai");
            }
            finally
            {
                await channel.ShutdownAsync();
            }
            return Response;
        }
    }
}
