using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace SumaTube.Infra.VideoSumarizer.Videos
{
    public class VideoSumarizerService
    {
        private static string _hostName = Environment.GetEnvironmentVariable("RABBITMQ_HOST") ?? "localhost";
        private static string _userName = Environment.GetEnvironmentVariable("RABBITMQ_USER") ?? "guest";
        private static string _password = Environment.GetEnvironmentVariable("RABBITMQ_PASSWORD") ?? "guest";
        private static string _queueName = "video-processing-queue";

        public async Task RequestVideoSummarization(string sessionId, string url, string language)
        {
            Console.WriteLine("### Video Processor Publisher ###");
            Console.WriteLine($"Conectando ao RabbitMQ em {_hostName}...");

            try
            {
                var factory = new ConnectionFactory()
                {
                    HostName = _hostName,
                    UserName = _userName,
                    Password = _password
                };

                using (var connection = await factory.CreateConnectionAsync())
                using (var channel = await connection.CreateChannelAsync())
                {
                    await channel.QueueDeclareAsync(
                                        queue: _queueName,
                                        durable: true,
                                        exclusive: false,
                                        autoDelete: false,
                                        arguments: null);

                    var properties = new BasicProperties
                    {
                        Persistent = true
                    };

                    Console.WriteLine("Conexão estabelecida com RabbitMQ");
                    Console.WriteLine("Pressione 'Ctrl+C' para sair");

                    // Loop para publicar mensagens
                    while (true)
                    {
                        if (string.IsNullOrWhiteSpace(language))
                            language = "pt";

                        // Criar objeto de mensagem
                        var message = new VideoProcessingMessageDocument(
                            sessionId,
                            url,
                            language);

                        // Serializar para JSON
                        var messageJson = JsonSerializer.Serialize(message);
                        var body = Encoding.UTF8.GetBytes(messageJson);

                        // Publicar mensagem
                        await channel.BasicPublishAsync(exchange: string.Empty,
                                           routingKey: _queueName,
                                           mandatory: true,
                                           basicProperties: properties,
                                           body: body);

                        Console.WriteLine($"[x] Mensagem enviada: {messageJson}");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Erro: {ex.Message}");
                Console.WriteLine(ex.StackTrace);
            }

            Console.WriteLine("Publicador finalizado.");
            Console.ReadLine();
        }
    }
}
