using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
using System.Text;
using System.Text.Json;

namespace BotManagerTestClient;

class Program
{
    static async Task Main(string[] args)
    {
        // Configure Serilog
        Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Debug()
            .WriteTo.Console()
            .WriteTo.File("logs/bot-manager-test-.txt", rollingInterval: RollingInterval.Day)
            .CreateLogger();

        var configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: false)
            .Build();

        var services = new ServiceCollection();
        services.AddLogging(builder => builder.AddSerilog());
        services.AddHttpClient();

        var serviceProvider = services.BuildServiceProvider();
        var httpClient = serviceProvider.GetRequiredService<HttpClient>();
        var logger = serviceProvider.GetRequiredService<ILogger<Program>>();

        var botManager = new BotManagerClient(httpClient, configuration, logger);

        logger.LogInformation("🤖 Starting Bot Manager Test Client...");

        try
        {
            // Test 1: Register with bot manager
            await botManager.RegisterBotAsync();

            // Test 2: Start some test sessions
            await botManager.SimulateUserSessions(5);

            // Test 3: Submit various metrics
            await botManager.SimulateMetrics();

            // Test 4: Send heartbeats
            await botManager.SendHeartbeats(3);

            logger.LogInformation("✅ All tests completed successfully!");
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "❌ Test failed");
        }

        Log.CloseAndFlush();
    }
}

public class BotManagerClient
{
    private readonly HttpClient _httpClient;
    private readonly IConfiguration _configuration;
    private readonly Microsoft.Extensions.Logging.ILogger _logger;
    private string? _apiKey;
    private Guid? _botId;

    public BotManagerClient(HttpClient httpClient, IConfiguration configuration, Microsoft.Extensions.Logging.ILogger logger)
    {
        _httpClient = httpClient;
        _configuration = configuration;
        _logger = logger;
    }

    public async Task RegisterBotAsync()
    {
        var apiUrl = _configuration["LittleShop:ApiUrl"];
        
        _logger.LogInformation("🔗 Connecting to LittleShop at {ApiUrl}", apiUrl);

        var registrationData = new
        {
            Name = "Local Test Bot",
            Description = "Local bot manager integration test",
            Type = 0, // Telegram
            Version = "1.0.0",
            InitialSettings = new Dictionary<string, object>
            {
                ["telegram"] = new { botToken = "test_token" },
                ["privacy"] = new { mode = "strict", enableTor = false }
            }
        };

        var json = JsonSerializer.Serialize(registrationData);
        var content = new StringContent(json, Encoding.UTF8, "application/json");

        _logger.LogInformation("📝 Registering bot with server...");
        var response = await _httpClient.PostAsync($"{apiUrl}/api/bots/register", content);

        if (response.IsSuccessStatusCode)
        {
            var responseJson = await response.Content.ReadAsStringAsync();
            var result = JsonSerializer.Deserialize<JsonElement>(responseJson);
            
            _apiKey = result.GetProperty("botKey").GetString();
            _botId = Guid.Parse(result.GetProperty("botId").GetString()!);
            
            _logger.LogInformation("✅ Bot registered successfully!");
            _logger.LogInformation("🔑 Bot ID: {BotId}", _botId);
            _logger.LogInformation("🔐 API Key: {ApiKey}", _apiKey);

            // Update platform info (simulate what a real bot would do)
            await UpdatePlatformInfoAsync();
        }
        else
        {
            _logger.LogError("❌ Failed to register bot: {StatusCode}", response.StatusCode);
            var errorContent = await response.Content.ReadAsStringAsync();
            _logger.LogError("Error details: {Error}", errorContent);
            throw new Exception($"Bot registration failed: {response.StatusCode}");
        }
    }

    public async Task SimulateUserSessions(int count)
    {
        if (string.IsNullOrEmpty(_apiKey)) throw new InvalidOperationException("Bot not registered");

        _logger.LogInformation("👥 Simulating {Count} user sessions...", count);

        for (int i = 1; i <= count; i++)
        {
            var sessionData = new
            {
                SessionIdentifier = $"local_test_session_{i}_{DateTime.Now.Ticks}",
                Platform = "TestClient",
                Language = "en",
                Country = "UK",
                IsAnonymous = true,
                Metadata = new { testRun = true, sessionNumber = i }
            };

            var json = JsonSerializer.Serialize(sessionData);
            var content = new StringContent(json, Encoding.UTF8, "application/json");
            
            _httpClient.DefaultRequestHeaders.Clear();
            _httpClient.DefaultRequestHeaders.Add("X-Bot-Key", _apiKey);

            var response = await _httpClient.PostAsync($"{_configuration["LittleShop:ApiUrl"]}/api/bots/sessions/start", content);
            
            if (response.IsSuccessStatusCode)
            {
                var responseJson = await response.Content.ReadAsStringAsync();
                var sessionResult = JsonSerializer.Deserialize<JsonElement>(responseJson);
                var sessionId = sessionResult.GetProperty("id").GetString();
                
                _logger.LogInformation("🎯 Session {Number} started: {SessionId}", i, sessionId);

                // Update session with some activity
                await Task.Delay(1000); // Simulate some activity
                
                var updateData = new
                {
                    MessageCount = new Random().Next(1, 10),
                    OrderCount = new Random().Next(0, 2),
                    TotalSpent = (decimal)(new Random().NextDouble() * 100)
                };

                var updateJson = JsonSerializer.Serialize(updateData);
                var updateContent = new StringContent(updateJson, Encoding.UTF8, "application/json");
                
                await _httpClient.PutAsync($"{_configuration["LittleShop:ApiUrl"]}/api/bots/sessions/{sessionId}", updateContent);
                
                _logger.LogInformation("📈 Session {Number} updated with activity", i);
            }
            else
            {
                _logger.LogWarning("⚠️ Failed to start session {Number}: {StatusCode}", i, response.StatusCode);
            }
        }
    }

    public async Task SimulateMetrics()
    {
        if (string.IsNullOrEmpty(_apiKey)) throw new InvalidOperationException("Bot not registered");

        _logger.LogInformation("📊 Submitting test metrics...");

        var metrics = new[]
        {
            new { MetricType = 0, Value = 15m, Category = "Users", Description = "User contacts" },
            new { MetricType = 4, Value = 42m, Category = "Messages", Description = "Messages sent" },
            new { MetricType = 2, Value = 3m, Category = "Orders", Description = "Orders processed" },
            new { MetricType = 6, Value = 1m, Category = "System", Description = "Errors logged" },
            new { MetricType = 10, Value = 250m, Category = "Performance", Description = "Avg response time ms" }
        };

        var batchData = new { Metrics = metrics };
        var json = JsonSerializer.Serialize(batchData);
        var content = new StringContent(json, Encoding.UTF8, "application/json");
        
        _httpClient.DefaultRequestHeaders.Clear();
        _httpClient.DefaultRequestHeaders.Add("X-Bot-Key", _apiKey);

        var response = await _httpClient.PostAsync($"{_configuration["LittleShop:ApiUrl"]}/api/bots/metrics/batch", content);
        
        if (response.IsSuccessStatusCode)
        {
            _logger.LogInformation("✅ Metrics submitted successfully!");
        }
        else
        {
            _logger.LogWarning("⚠️ Failed to submit metrics: {StatusCode}", response.StatusCode);
        }
    }

    public async Task SendHeartbeats(int count)
    {
        if (string.IsNullOrEmpty(_apiKey)) throw new InvalidOperationException("Bot not registered");

        _logger.LogInformation("💓 Sending {Count} heartbeats...", count);

        for (int i = 1; i <= count; i++)
        {
            var heartbeatData = new
            {
                Version = "1.0.0",
                IpAddress = "127.0.0.1",
                ActiveSessions = new Random().Next(0, 5),
                Status = new { healthy = true, uptime = DateTime.UtcNow.Ticks }
            };

            var json = JsonSerializer.Serialize(heartbeatData);
            var content = new StringContent(json, Encoding.UTF8, "application/json");
            
            _httpClient.DefaultRequestHeaders.Clear();
            _httpClient.DefaultRequestHeaders.Add("X-Bot-Key", _apiKey);

            var response = await _httpClient.PostAsync($"{_configuration["LittleShop:ApiUrl"]}/api/bots/heartbeat", content);
            
            if (response.IsSuccessStatusCode)
            {
                _logger.LogInformation("💓 Heartbeat {Number} sent successfully", i);
            }
            else
            {
                _logger.LogWarning("⚠️ Heartbeat {Number} failed: {StatusCode}", i, response.StatusCode);
            }

            if (i < count) await Task.Delay(2000); // Wait between heartbeats
        }
    }

    public async Task UpdatePlatformInfoAsync()
    {
        if (string.IsNullOrEmpty(_apiKey)) throw new InvalidOperationException("Bot not registered");

        _logger.LogInformation("📱 Updating platform information...");

        var platformInfo = new
        {
            PlatformUsername = "littleshop_testbot",
            PlatformDisplayName = "LittleShop Test Bot",
            PlatformId = "123456789" // Would be actual bot ID from Telegram
        };

        var json = JsonSerializer.Serialize(platformInfo);
        var content = new StringContent(json, Encoding.UTF8, "application/json");
        
        _httpClient.DefaultRequestHeaders.Clear();
        _httpClient.DefaultRequestHeaders.Add("X-Bot-Key", _apiKey);

        var response = await _httpClient.PutAsync($"{_configuration["LittleShop:ApiUrl"]}/api/bots/platform-info", content);
        
        if (response.IsSuccessStatusCode)
        {
            _logger.LogInformation("✅ Platform info updated: @{Username} ({DisplayName})", 
                platformInfo.PlatformUsername, platformInfo.PlatformDisplayName);
        }
        else
        {
            _logger.LogWarning("⚠️ Failed to update platform info: {StatusCode}", response.StatusCode);
        }
    }
}