/*
 * File: D:\shadowed-realms-mobile\ShadowedRealmsMobile\src\server\ShadowedRealms.Admin\Services\KingdomManagementService.cs
 * Created: 2025-11-04
 * Last Modified: 2025-11-04
 * Description: Service layer for Kingdom Management admin features with real database integration using Entity Framework Core
 * Last Edit Notes: FIXED - Both kingdom and alliance health score calculations corrected
 */

using Microsoft.EntityFrameworkCore;
using ShadowedRealms.Data.Contexts;
using ShadowedRealms.Admin.Models;

namespace ShadowedRealms.Admin.Services
{
    /// <summary>
    /// Interface for Kingdom Management admin operations
    /// </summary>
    public interface IKingdomManagementService
    {
        Task<KingdomDashboardViewModel> GetKingdomDashboardAsync();
        Task<KingdomHealthViewModel> GetKingdomHealthAsync(int kingdomId);
        Task<DemocraticSystemsViewModel> GetDemocraticSystemsAsync(int kingdomId);
        Task<KingdomMergersViewModel> GetKingdomMergersAsync();
        Task<AllianceAdministrationViewModel> GetAllianceAdministrationAsync(int kingdomId);
        Task<KvKManagementViewModel> GetKvKManagementAsync();
    }

    /// <summary>
    /// Service for Kingdom Management admin operations with database integration
    /// </summary>
    public class KingdomManagementService : IKingdomManagementService
    {
        private readonly GameDbContext _context;
        private readonly ILogger<KingdomManagementService> _logger;

        public KingdomManagementService(
            GameDbContext context,
            ILogger<KingdomManagementService> logger)
        {
            _context = context;
            _logger = logger;
        }

        #region Kingdom Dashboard

        /// <summary>
        /// Get kingdom dashboard overview with real database statistics - FIXED TO USE REAL PLAYER COUNTS
        /// </summary>
        public async Task<KingdomDashboardViewModel> GetKingdomDashboardAsync()
        {
            try
            {
                _logger.LogInformation("Fetching kingdom dashboard data from database");

                // Get total kingdoms from database
                var totalKingdoms = await _context.Kingdoms
                    .Where(k => k.IsActive)
                    .CountAsync();

                // Get total ACTIVE population across all kingdoms (this is correct - it's the sum)
                var totalPopulation = await _context.Players
                    .Where(p => p.IsActive)
                    .CountAsync();

                // Get total active alliances
                var activeAlliances = await _context.Alliances
                    .Where(a => a.IsActive)
                    .CountAsync();

                // FIXED: Get kingdom summaries with REAL-TIME player counts from Players table
                var kingdoms = await _context.Kingdoms
                    .Where(k => k.IsActive)
                    .Select(k => new
                    {
                        k.Id,
                        k.Name,
                        k.Number,
                        // FIX: Calculate real-time population from Players table
                        CurrentPopulation = _context.Players
                            .Count(p => p.KingdomId == k.Id && p.IsActive),
                        k.MaxPopulation,
                        k.CreatedAt,
                        // FIX: Calculate alliance count from Alliances table
                        AllianceCount = _context.Alliances
                            .Count(a => a.KingdomId == k.Id && a.IsActive),
                        // FIX: Calculate active players from Players table
                        ActivePlayerCount = _context.Players
                            .Count(p => p.KingdomId == k.Id && p.IsActive &&
                                   p.LastActiveAt >= DateTime.UtcNow.AddDays(-7)),
                        // FIX: Get last combat date from CombatLogs
                        LastCombatDate = _context.CombatLogs
                            .Where(c => c.AttackerPlayer.KingdomId == k.Id ||
                                   c.DefenderPlayer.KingdomId == k.Id)
                            .OrderByDescending(c => c.Timestamp)
                            .Select(c => (DateTime?)c.Timestamp)
                            .FirstOrDefault()
                    })
                    .OrderByDescending(k => k.CurrentPopulation) // Order by real player count
                    .ToListAsync();

                // Calculate health alerts based on kingdom metrics
                int healthAlerts = kingdoms.Count(k =>
                    (decimal)k.CurrentPopulation / k.MaxPopulation < 0.5m || // Low population
                    k.AllianceCount < 5); // Few alliances

                var viewModel = new KingdomDashboardViewModel
                {
                    TotalKingdoms = totalKingdoms,
                    TotalPopulation = totalPopulation, // Total ACTIVE players across all kingdoms
                    ActiveAlliances = activeAlliances,
                    HealthAlerts = healthAlerts,
                    LastUpdated = DateTime.UtcNow,
                    Kingdoms = kingdoms.Select(k => new KingdomSummary
                    {
                        Id = k.Id,
                        Name = k.Name,
                        Population = k.CurrentPopulation, // Real-time count from Players table
                        MaxCapacity = k.MaxPopulation,
                        HealthScore = CalculateKingdomHealthScore(
                            k.CurrentPopulation,
                            k.MaxPopulation,
                            k.ActivePlayerCount,
                            k.AllianceCount),
                        ActiveAlliances = k.AllianceCount,
                        LastKvKDate = k.LastCombatDate
                    }).ToList()
                };

                _logger.LogInformation("Kingdom dashboard data retrieved successfully with {KingdomCount} kingdoms and {TotalPopulation} active players",
                    totalKingdoms, totalPopulation);

                return viewModel;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error fetching kingdom dashboard data");
                throw;
            }
        }

        #endregion

        #region Kingdom Health

        /// <summary>
        /// Get detailed kingdom health metrics from database - FIXED alliance ordering
        /// </summary>
        public async Task<KingdomHealthViewModel> GetKingdomHealthAsync(int kingdomId)
        {
            try
            {
                _logger.LogInformation("Fetching kingdom health data for kingdom {KingdomId}", kingdomId);

                var kingdom = await _context.Kingdoms
                    .FirstOrDefaultAsync(k => k.Id == kingdomId);

                if (kingdom == null)
                {
                    throw new InvalidOperationException($"Kingdom {kingdomId} not found");
                }

                var today = DateTime.UtcNow.Date;
                var weekAgo = today.AddDays(-7);

                // Get population metrics - ALL FROM REAL DATABASE QUERIES
                var totalPopulation = await _context.Players
                    .CountAsync(p => p.KingdomId == kingdomId && p.IsActive);

                var activePlayersToday = await _context.Players
                    .CountAsync(p => p.KingdomId == kingdomId &&
                           p.IsActive &&
                           p.LastActiveAt >= today);

                var activePlayersWeek = await _context.Players
                    .CountAsync(p => p.KingdomId == kingdomId &&
                           p.IsActive &&
                           p.LastActiveAt >= weekAgo);

                var newPlayersThisWeek = await _context.Players
                    .CountAsync(p => p.KingdomId == kingdomId &&
                           p.CreatedAt >= weekAgo);

                var inactivePlayers = await _context.Players
                    .CountAsync(p => p.KingdomId == kingdomId &&
                           p.IsActive &&
                           p.LastActiveAt < weekAgo);

                // FIXED: Get alliance health data - calculate member count in SQL query instead of using computed property
                var allianceHealthData = await _context.Alliances
                    .Where(a => a.KingdomId == kingdomId && a.IsActive)
                    .Select(a => new
                    {
                        a.Name,
                        // FIX: Calculate member count directly in the query
                        MemberCount = _context.Players.Count(p => p.AllianceId == a.Id && p.IsActive),
                        a.Level,
                        a.Id,
                        ActiveMembers = _context.Players
                            .Count(p => p.AllianceId == a.Id &&
                                   p.IsActive &&
                                   p.LastActiveAt >= weekAgo),
                        RecentJoins = _context.Players
                            .Count(p => p.AllianceId == a.Id &&
                                   p.CreatedAt >= weekAgo)
                    })
                    .OrderByDescending(a => a.MemberCount)  // Now this works!
                    .Take(10)
                    .ToListAsync();

                // Get recent combat activity
                var recentCombats = await _context.CombatLogs
                    .Where(c => (c.AttackerPlayer.KingdomId == kingdomId ||
                            c.DefenderPlayer.KingdomId == kingdomId) &&
                           c.Timestamp >= weekAgo)
                    .CountAsync();

                // Calculate health scores
                var populationScore = totalPopulation > 0
                    ? Math.Min(100m, (decimal)totalPopulation / kingdom.MaxPopulation * 100m)
                    : 0m;

                var retentionScore = totalPopulation > 0
                    ? (decimal)activePlayersWeek / totalPopulation * 100m
                    : 0m;

                var allianceActivityScore = allianceHealthData.Any()
                    ? allianceHealthData.Average(a =>
                        a.MemberCount > 0 ? (decimal)a.ActiveMembers / a.MemberCount * 100m : 0m)
                    : 0m;

                var combatActivityScore = totalPopulation > 0
                    ? Math.Min(100m, (decimal)recentCombats / totalPopulation * 10m)
                    : 0m;

                var overallHealthScore = (populationScore + retentionScore + allianceActivityScore + combatActivityScore) / 4m;

                var viewModel = new KingdomHealthViewModel
                {
                    KingdomId = kingdomId,
                    KingdomName = kingdom.Name,
                    OverallHealthScore = Math.Round(overallHealthScore, 1),
                    HealthTrend = 0m, // TODO: Calculate trend from historical data

                    // Population metrics - ALL FROM REAL DATABASE
                    PopulationScore = Math.Round(populationScore, 1),
                    RetentionScore = Math.Round(retentionScore, 1),
                    TotalPopulation = totalPopulation,
                    ActivePlayersToday = activePlayersToday,
                    ActivePlayersWeek = activePlayersWeek,
                    NewPlayersThisWeek = newPlayersThisWeek,
                    InactivePlayers = inactivePlayers,
                    MaxCapacity = kingdom.MaxPopulation,

                    // Health scores
                    AllianceActivityScore = Math.Round(allianceActivityScore, 1),
                    EconomicScore = 85.0m, // TODO: Calculate from purchase logs
                    CombatActivityScore = Math.Round(combatActivityScore, 1),
                    DemocraticScore = 75.0m, // TODO: Calculate from voting data when implemented

                    // Alliance health data
                    AllianceHealthData = allianceHealthData.Select(a => new AllianceHealthData
                    {
                        Name = a.Name,
                        HealthScore = a.MemberCount > 0
                            ? Math.Round((decimal)a.ActiveMembers / a.MemberCount * 100m, 1)
                            : 0m,
                        MemberCount = a.MemberCount,
                        ActivityLevel = a.MemberCount > 0
                            ? Math.Round((decimal)a.ActiveMembers / a.MemberCount * 100m, 1)
                            : 0m,
                        GrowthRate = a.MemberCount > 0
                            ? Math.Round((decimal)a.RecentJoins / a.MemberCount * 100m, 1)
                            : 0m
                    }).ToList(),

                    // Recent activities - Generate from database events
                    RecentActivities = await GetRecentActivitiesAsync(kingdomId),

                    // Health alerts
                    HealthAlerts = GenerateHealthAlerts(
                        populationScore,
                        retentionScore,
                        allianceActivityScore,
                        combatActivityScore),

                    LastUpdated = DateTime.UtcNow
                };

                _logger.LogInformation("Kingdom health data retrieved for kingdom {KingdomId} with {TotalPopulation} players",
                    kingdomId, totalPopulation);

                return viewModel;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error fetching kingdom health for kingdom {KingdomId}", kingdomId);
                throw;
            }
        }

        #endregion

        #region Democratic Systems

        /// <summary>
        /// Get democratic systems data for kingdom from database
        /// </summary>
        public async Task<DemocraticSystemsViewModel> GetDemocraticSystemsAsync(int kingdomId)
        {
            try
            {
                _logger.LogInformation("Fetching democratic systems data for kingdom {KingdomId}", kingdomId);

                var kingdom = await _context.Kingdoms
                    .FirstOrDefaultAsync(k => k.Id == kingdomId);

                if (kingdom == null)
                {
                    throw new InvalidOperationException($"Kingdom {kingdomId} not found");
                }

                // TODO: When voting/democracy tables are implemented, replace with real queries
                // For now, providing structure with placeholder calculations

                var viewModel = new DemocraticSystemsViewModel
                {
                    KingdomId = kingdomId,
                    KingdomName = kingdom.Name,
                    VoterTurnoutRate = 0m, // TODO: Calculate from voting records
                    ActiveCandidates = 0,
                    GovernanceScore = 75.0m, // TODO: Calculate from governance metrics
                    TaxDistributionTransparency = 90.0m, // TODO: Calculate from tax logs
                    CurrentLeadership = new List<CurrentLeader>(), // TODO: Load from leadership table
                    ActiveElections = new List<ActiveElection>(), // TODO: Load from elections table
                    TaxDistributions = new List<TaxDistribution>(), // TODO: Load from tax distribution table
                    TotalTaxCollected = 0L, // TODO: Sum from tax logs
                    TotalTaxDistributed = 0L, // TODO: Sum from distribution logs
                    LastDistributionDate = DateTime.MinValue, // TODO: Get from last distribution record
                    GovernanceAlerts = new List<GovernanceAlert>(),
                    LastUpdated = DateTime.UtcNow
                };

                _logger.LogInformation("Democratic systems data retrieved for kingdom {KingdomId}", kingdomId);
                return viewModel;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error fetching democratic systems for kingdom {KingdomId}", kingdomId);
                throw;
            }
        }

        #endregion

        #region Kingdom Mergers

        /// <summary>
        /// Get kingdom merger proposals from database
        /// </summary>
        public async Task<KingdomMergersViewModel> GetKingdomMergersAsync()
        {
            try
            {
                _logger.LogInformation("Fetching kingdom merger data");

                // Get available kingdoms with REAL player counts
                var availableKingdoms = await _context.Kingdoms
                    .Where(k => k.IsActive)
                    .OrderBy(k => k.Number)
                    .Select(k => new KingdomOption
                    {
                        Id = k.Id,
                        Name = k.Name,
                        // FIX: Use real-time player count
                        Population = _context.Players.Count(p => p.KingdomId == k.Id && p.IsActive)
                    })
                    .ToListAsync();

                var viewModel = new KingdomMergersViewModel
                {
                    PendingProposals = 0, // TODO: Count from merger proposals table
                    ActiveMergers = 0,
                    CompletedMergers = 0,
                    RejectedProposals = 0,
                    MergerProposals = new List<MergerProposalDetails>(), // TODO: Load from merger table
                    AvailableKingdoms = availableKingdoms,
                    LastUpdated = DateTime.UtcNow
                };

                _logger.LogInformation("Kingdom merger data retrieved");
                return viewModel;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error fetching kingdom merger data");
                throw;
            }
        }

        #endregion

        #region Alliance Administration

        /// <summary>
        /// Get alliance administration data for kingdom from database - FIXED alliance ordering
        /// </summary>
        public async Task<AllianceAdministrationViewModel> GetAllianceAdministrationAsync(int kingdomId)
        {
            try
            {
                _logger.LogInformation("Fetching alliance administration data for kingdom {KingdomId}", kingdomId);

                var kingdom = await _context.Kingdoms
                    .FirstOrDefaultAsync(k => k.Id == kingdomId);

                if (kingdom == null)
                {
                    throw new InvalidOperationException($"Kingdom {kingdomId} not found");
                }

                var weekAgo = DateTime.UtcNow.AddDays(-7);

                // Get alliance statistics
                var totalAlliances = await _context.Alliances
                    .CountAsync(a => a.KingdomId == kingdomId && a.IsActive);

                var totalMembers = await _context.Players
                    .CountAsync(p => p.KingdomId == kingdomId &&
                           p.AllianceId != null &&
                           p.IsActive);

                // FIXED: Get detailed alliance data - calculate member count in SQL query
                var alliances = await _context.Alliances
                    .Where(a => a.KingdomId == kingdomId && a.IsActive)
                    .Select(a => new
                    {
                        AllianceId = a.Id,
                        a.Name,
                        a.Description,
                        a.Level,
                        // FIX: Calculate member count directly in query
                        MemberCount = _context.Players.Count(p => p.AllianceId == a.Id && p.IsActive),
                        a.CreatedAt,
                        ActiveMembers = _context.Players
                            .Count(p => p.AllianceId == a.Id &&
                                   p.IsActive &&
                                   p.LastActiveAt >= weekAgo),
                        TotalPower = _context.Players
                            .Where(p => p.AllianceId == a.Id && p.IsActive)
                            .Sum(p => (long?)p.Power) ?? 0,
                        RecentCombats = _context.CombatLogs
                            .Count(c => (c.AttackerPlayer.AllianceId == a.Id ||
                                    c.DefenderPlayer.AllianceId == a.Id) &&
                                   c.Timestamp >= weekAgo)
                    })
                    .OrderByDescending(a => a.MemberCount)  // Now this works!
                    .ToListAsync();

                // Calculate alliances needing attention
                var alliancesNeedingAttention = alliances.Count(a =>
                    a.MemberCount < 10 || // Very small alliance
                    (a.MemberCount > 0 && (decimal)a.ActiveMembers / a.MemberCount < 0.3m)); // Low activity

                var viewModel = new AllianceAdministrationViewModel
                {
                    KingdomId = kingdomId,
                    KingdomName = kingdom.Name,
                    TotalAlliances = totalAlliances,
                    ActiveCoalitions = 0, // TODO: Count from coalition table when implemented
                    TotalMembers = totalMembers,
                    AlliancesNeedingAttention = alliancesNeedingAttention,
                    Alliances = alliances.Select(a => new AllianceDetails
                    {
                        AllianceId = a.AllianceId,
                        Name = a.Name,
                        Description = a.Description ?? "No description",
                        Level = a.Level,
                        FoundedDate = a.CreatedAt,
                        Status = "Active",
                        MemberCount = a.MemberCount,
                        PowerRating = (long)a.TotalPower,
                        ActivityLevel = a.MemberCount > 0
                            ? Math.Round((decimal)a.ActiveMembers / a.MemberCount * 100m, 1)
                            : 0m,
                        HealthScore = CalculateAllianceHealth(
                            a.MemberCount,
                            a.ActiveMembers,
                            a.RecentCombats),
                        LastActivityDate = a.CreatedAt,
                        CoalitionName = null, // TODO: Load from coalition table
                        Leadership = new List<LeadershipMember>() // TODO: Load from alliance roles
                    }).ToList(),
                    ActiveCoalitionDetails = new List<CoalitionDetails>(), // TODO: Load coalition data
                    AllianceAlerts = GenerateAllianceAlerts(alliances.Cast<dynamic>().ToList()),
                    LastUpdated = DateTime.UtcNow
                };

                _logger.LogInformation("Alliance administration data retrieved for kingdom {KingdomId}", kingdomId);
                return viewModel;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error fetching alliance administration for kingdom {KingdomId}", kingdomId);
                throw;
            }
        }

        #endregion

        #region KvK Management

        /// <summary>
        /// Get KvK event management data from database
        /// </summary>
        public async Task<KvKManagementViewModel> GetKvKManagementAsync()
        {
            try
            {
                _logger.LogInformation("Fetching KvK event management data");

                // Get available kingdoms with REAL player counts
                var availableKingdoms = await _context.Kingdoms
                    .Where(k => k.IsActive)
                    .OrderBy(k => k.Number)
                    .Select(k => new KingdomOption
                    {
                        Id = k.Id,
                        Name = k.Name,
                        // FIX: Use real-time player count
                        Population = _context.Players.Count(p => p.KingdomId == k.Id && p.IsActive)
                    })
                    .ToListAsync();

                var viewModel = new KvKManagementViewModel
                {
                    ActiveEvents = 0, // TODO: Count active KvK events
                    UpcomingEvents = 0, // TODO: Count scheduled events
                    ParticipatingKingdoms = 0,
                    CompletedToday = 0,
                    AutoMatchmakingEnabled = true,
                    KvKEvents = new List<KvKEventDetails>(), // TODO: Load from KvK events table
                    AvailableKingdoms = availableKingdoms,
                    LastUpdated = DateTime.UtcNow
                };

                _logger.LogInformation("KvK event management data retrieved");
                return viewModel;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error fetching KvK event management data");
                throw;
            }
        }

        #endregion

        #region Helper Methods

        /// <summary>
        /// Calculate kingdom health score from metrics - FIXED to not multiply by 100
        /// </summary>
        private decimal CalculateKingdomHealthScore(
            int currentPopulation,
            int maxPopulation,
            int activePlayerCount,
            int allianceCount)
        {
            if (maxPopulation == 0) return 0m;

            var populationRatio = (decimal)currentPopulation / maxPopulation;
            var activityRatio = currentPopulation > 0
                ? (decimal)activePlayerCount / currentPopulation
                : 0m;
            var allianceScore = Math.Min(1m, allianceCount / 20m); // 20 alliances = perfect score

            var healthScore = (populationRatio * 40m) + (activityRatio * 40m) + (allianceScore * 20m);
            return Math.Round(healthScore, 1);  // FIXED: Removed * 100m
        }

        /// <summary>
        /// Calculate alliance health score - FIXED to not multiply by 100
        /// </summary>
        private decimal CalculateAllianceHealth(int memberCount, int activeMembers, int recentCombats)
        {
            if (memberCount == 0) return 0m;

            var activityRatio = (decimal)activeMembers / memberCount;
            var combatScore = Math.Min(1m, recentCombats / 10m);
            var sizeScore = Math.Min(1m, memberCount / 100m);

            var healthScore = (activityRatio * 50m) + (combatScore * 30m) + (sizeScore * 20m);
            return Math.Round(healthScore, 1);  // FIXED: Removed * 100m
        }

        /// <summary>
        /// Get recent activities for a kingdom
        /// </summary>
        private async Task<List<ActivityItem>> GetRecentActivitiesAsync(int kingdomId)
        {
            var activities = new List<ActivityItem>();
            var weekAgo = DateTime.UtcNow.AddDays(-7);

            // Recent combat activities
            var recentCombatCount = await _context.CombatLogs
                .Where(c => (c.AttackerPlayer.KingdomId == kingdomId ||
                        c.DefenderPlayer.KingdomId == kingdomId) &&
                       c.Timestamp >= weekAgo)
                .CountAsync();

            if (recentCombatCount > 50)
            {
                activities.Add(new ActivityItem
                {
                    Title = "High Combat Activity",
                    Description = $"{recentCombatCount} battles recorded in the past week",
                    Category = "Combat",
                    Severity = "Info",
                    Timestamp = DateTime.UtcNow.AddHours(-2)
                });
            }

            // New player registrations
            var newPlayers = await _context.Players
                .CountAsync(p => p.KingdomId == kingdomId && p.CreatedAt >= weekAgo);

            if (newPlayers > 10)
            {
                activities.Add(new ActivityItem
                {
                    Title = "New Player Influx",
                    Description = $"{newPlayers} new players joined this week",
                    Category = "Population",
                    Severity = "Success",
                    Timestamp = DateTime.UtcNow.AddHours(-5)
                });
            }

            return activities;
        }

        /// <summary>
        /// Generate health alerts based on metrics
        /// </summary>
        private List<HealthAlert> GenerateHealthAlerts(
            decimal populationScore,
            decimal retentionScore,
            decimal allianceActivityScore,
            decimal combatActivityScore)
        {
            var alerts = new List<HealthAlert>();

            if (populationScore < 50m)
            {
                alerts.Add(new HealthAlert
                {
                    Id = "HEALTH_POP",
                    Title = "Low Population Warning",
                    Description = "Kingdom population is below 50% capacity",
                    Severity = "Warning",
                    Timestamp = DateTime.UtcNow
                });
            }

            if (retentionScore < 60m)
            {
                alerts.Add(new HealthAlert
                {
                    Id = "HEALTH_RET",
                    Title = "Player Retention Issue",
                    Description = "Less than 60% of players active in past week",
                    Severity = "Warning",
                    Timestamp = DateTime.UtcNow
                });
            }

            if (allianceActivityScore < 50m)
            {
                alerts.Add(new HealthAlert
                {
                    Id = "HEALTH_ALI",
                    Title = "Alliance Activity Warning",
                    Description = "Alliance member activity below healthy levels",
                    Severity = "Warning",
                    Timestamp = DateTime.UtcNow
                });
            }

            return alerts;
        }

        /// <summary>
        /// Generate alliance alerts based on data
        /// </summary>
        private List<AllianceAlert> GenerateAllianceAlerts(List<dynamic> alliances)
        {
            var alerts = new List<AllianceAlert>();

            foreach (var alliance in alliances)
            {
                int allianceId = alliance.AllianceId;
                string name = alliance.Name;
                int memberCount = alliance.MemberCount;
                int activeMembers = alliance.ActiveMembers;

                if (memberCount < 10)
                {
                    alerts.Add(new AllianceAlert
                    {
                        Id = $"ALI_{allianceId}_SIZE",
                        AllianceName = name,
                        Severity = "Info",
                        Description = "Alliance has very few members - may need recruitment support",
                        Timestamp = DateTime.UtcNow
                    });
                }

                if (memberCount > 0 &&
                    (decimal)activeMembers / memberCount < 0.3m)
                {
                    alerts.Add(new AllianceAlert
                    {
                        Id = $"ALI_{allianceId}_ACT",
                        AllianceName = name,
                        Severity = "Warning",
                        Description = "Alliance has low member activity - less than 30% active",
                        Timestamp = DateTime.UtcNow
                    });
                }
            }

            return alerts;
        }

        #endregion
    }
}