/*
 * File: D:\shadowed-realms-mobile\ShadowedRealmsMobile\src\server\ShadowedRealms.API\Services\AllianceService.cs
 * Created: 2025-10-19
 * Last Modified: 2025-10-23
 * Description: Concrete implementation of IAllianceService providing comprehensive alliance-related business logic operations including coalition system (core innovation), research trees, territory management, democratic decision-making, and multi-alliance coordination while preserving individual alliance identity
 * Last Edit Notes: Fixed UnitOfWork signature and entity property references to match actual Player and Alliance models
 */

using Microsoft.Extensions.Logging;
using ShadowedRealms.Core.Interfaces;
using ShadowedRealms.Core.Interfaces.Repositories;
using ShadowedRealms.Core.Interfaces.Services;
using ShadowedRealms.Core.Models;
using ShadowedRealms.Core.Models.Alliance;
using ShadowedRealms.Core.Models.Player;

namespace ShadowedRealms.API.Services
{
    /// <summary>
    /// Concrete implementation of alliance service providing comprehensive business logic coordination for all alliance-related operations
    /// </summary>
    public class AllianceService : IAllianceService
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly IAllianceRepository _allianceRepository;
        private readonly IPlayerRepository _playerRepository;
        private readonly IKingdomRepository _kingdomRepository;
        private readonly ICombatLogRepository _combatLogRepository;
        private readonly IPurchaseLogRepository _purchaseLogRepository;
        private readonly ILogger<AllianceService> _logger;

        // Alliance constants for balance and limits
        private const int MAX_ALLIANCE_SIZE = 100; // Maximum members per alliance
        private const int MIN_COALITION_MEMBERS = 50; // Minimum combined members for coalition
        private const double COALITION_VOTING_QUORUM = 0.6; // 60% member participation required
        private const int MAX_RESEARCH_LEVEL = 50; // Maximum research level per branch
        private const int MAX_ALLIANCE_LEVEL = 30; // Maximum alliance level
        private const double DEMOCRATIC_VOTING_QUORUM = 0.5; // 50% member participation for decisions

        public AllianceService(
            IUnitOfWork unitOfWork,
            IAllianceRepository allianceRepository,
            IPlayerRepository playerRepository,
            IKingdomRepository kingdomRepository,
            ICombatLogRepository combatLogRepository,
            IPurchaseLogRepository purchaseLogRepository,
            ILogger<AllianceService> logger)
        {
            _unitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork));
            _allianceRepository = allianceRepository ?? throw new ArgumentNullException(nameof(allianceRepository));
            _playerRepository = playerRepository ?? throw new ArgumentNullException(nameof(playerRepository));
            _kingdomRepository = kingdomRepository ?? throw new ArgumentNullException(nameof(kingdomRepository));
            _combatLogRepository = combatLogRepository ?? throw new ArgumentNullException(nameof(combatLogRepository));
            _purchaseLogRepository = purchaseLogRepository ?? throw new ArgumentNullException(nameof(purchaseLogRepository));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
        }

        #region Coalition System (Core Innovation)

        public async Task<(bool Success, string CoalitionId, Dictionary<string, object> VotingRequirements, DateTime VotingDeadline)>
            FormCoalitionAsync(int initiatingAllianceId, List<int> targetAllianceIds, int kingdomId, string coalitionType,
                Dictionary<string, object> proposedTerms)
        {
            _logger.LogInformation("Forming coalition: Alliance {InitiatingId} with targets {TargetIds}, Type: {CoalitionType}",
                initiatingAllianceId, string.Join(",", targetAllianceIds), coalitionType);

            return await _unitOfWork.ExecuteInTransactionAsync(async (unitOfWork) =>
            {
                // Validate initiating alliance
                var initiatingAlliance = await _allianceRepository.GetByIdAsync(initiatingAllianceId, kingdomId);
                if (initiatingAlliance == null)
                    throw new ArgumentException($"Initiating alliance {initiatingAllianceId} not found");

                // Validate target alliances
                var targetAlliances = new List<Alliance>();
                var totalMembers = initiatingAlliance.MemberCount;

                foreach (var targetId in targetAllianceIds)
                {
                    var alliance = await _allianceRepository.GetByIdAsync(targetId, kingdomId);
                    if (alliance == null)
                    {
                        return (false, "", new Dictionary<string, object>
                        {
                            ["Error"] = $"Target alliance {targetId} not found"
                        }, DateTime.UtcNow);
                    }
                    targetAlliances.Add(alliance);
                    totalMembers += alliance.MemberCount;
                }

                // Validate coalition requirements
                if (totalMembers < MIN_COALITION_MEMBERS)
                {
                    return (false, "", new Dictionary<string, object>
                    {
                        ["Error"] = $"Coalition requires minimum {MIN_COALITION_MEMBERS} combined members, has {totalMembers}"
                    }, DateTime.UtcNow);
                }

                // Generate unique coalition ID
                var coalitionId = $"COALITION_{initiatingAllianceId}_{DateTime.UtcNow.Ticks}";

                // Calculate voting requirements
                var votingRequirements = new Dictionary<string, object>
                {
                    ["CoalitionId"] = coalitionId,
                    ["InitiatingAlliance"] = new { Id = initiatingAllianceId, Name = initiatingAlliance.Name },
                    ["TargetAlliances"] = targetAlliances.Select(a => new { Id = a.Id, Name = a.Name }).ToList(),
                    ["CoalitionType"] = coalitionType,
                    ["ProposedTerms"] = proposedTerms,
                    ["RequiredQuorum"] = COALITION_VOTING_QUORUM,
                    ["TotalMembers"] = totalMembers,
                    ["VotingDeadline"] = DateTime.UtcNow.AddDays(3) // 3 days to vote
                };

                // Create coalition proposal
                var coalitionProposal = new Dictionary<string, object>
                {
                    ["CoalitionId"] = coalitionId,
                    ["InitiatingAllianceId"] = initiatingAllianceId,
                    ["TargetAllianceIds"] = targetAllianceIds,
                    ["CoalitionType"] = coalitionType,
                    ["ProposedTerms"] = proposedTerms,
                    ["Status"] = "Voting",
                    ["CreatedAt"] = DateTime.UtcNow,
                    ["VotingDeadline"] = votingRequirements["VotingDeadline"]
                };

                // Store coalition proposal (would be in coalition management system)
                await StoreCoalitionProposal(coalitionId, coalitionProposal, kingdomId);

                // Notify all target alliances of coalition proposal
                foreach (var alliance in targetAlliances)
                {
                    await NotifyAllianceOfCoalitionProposal(alliance.Id, kingdomId, coalitionProposal);
                }

                _logger.LogInformation("Coalition proposal created: {CoalitionId}, Voting deadline: {Deadline}",
                    coalitionId, votingRequirements["VotingDeadline"]);

                return (true, coalitionId, votingRequirements, (DateTime)votingRequirements["VotingDeadline"]);
            });
        }

        public async Task<(bool VotePassed, double ApprovalPercentage, Dictionary<string, object> CoalitionStatus)>
            ProcessCoalitionVotingAsync(int allianceId, string coalitionId, int kingdomId,
                Dictionary<int, bool> votingResults)
        {
            _logger.LogInformation("Processing coalition voting: Alliance {AllianceId}, Coalition {CoalitionId}, Votes: {VoteCount}",
                allianceId, coalitionId, votingResults.Count);

            return await _unitOfWork.ExecuteInTransactionAsync(async (unitOfWork) =>
            {
                var alliance = await _allianceRepository.GetByIdAsync(allianceId, kingdomId);
                if (alliance == null)
                    throw new ArgumentException($"Alliance {allianceId} not found");

                // Get coalition proposal
                var coalitionProposal = await GetCoalitionProposal(coalitionId, kingdomId);
                if (coalitionProposal == null)
                {
                    return (false, 0.0, new Dictionary<string, object> { ["Error"] = "Coalition proposal not found" });
                }

                // Validate voting eligibility
                var eligibleVoters = await GetAllianceActiveMembers(allianceId, kingdomId);
                var validVotes = 0;
                var approvalVotes = 0;

                foreach (var vote in votingResults)
                {
                    var playerId = vote.Key;
                    var voteValue = vote.Value;

                    // Check if player is eligible to vote - Fixed: Use Id instead of PlayerId
                    if (eligibleVoters.Any(v => v.Id == playerId))
                    {
                        validVotes++;
                        if (voteValue) approvalVotes++;
                    }
                }

                var totalEligibleVoters = eligibleVoters.Count;
                var participationRate = (double)validVotes / totalEligibleVoters;
                var approvalPercentage = validVotes > 0 ? (double)approvalVotes / validVotes : 0.0;

                var coalitionStatus = new Dictionary<string, object>
                {
                    ["CoalitionId"] = coalitionId,
                    ["AllianceId"] = allianceId,
                    ["AllianceName"] = alliance.Name,
                    ["TotalEligibleVoters"] = totalEligibleVoters,
                    ["VotesReceived"] = validVotes,
                    ["ParticipationRate"] = participationRate,
                    ["ApprovalVotes"] = approvalVotes,
                    ["RejectionVotes"] = validVotes - approvalVotes,
                    ["ApprovalPercentage"] = approvalPercentage,
                    ["QuorumMet"] = participationRate >= COALITION_VOTING_QUORUM,
                    ["VotePassed"] = participationRate >= COALITION_VOTING_QUORUM && approvalPercentage >= 0.6
                };

                // Store voting results
                await StoreCoalitionVotingResults(coalitionId, allianceId, kingdomId, coalitionStatus);

                var votePassed = (bool)coalitionStatus["VotePassed"];

                if (votePassed)
                {
                    _logger.LogInformation("Coalition vote passed for Alliance {AllianceId}: {ApprovalPercentage}% approval",
                        allianceId, approvalPercentage * 100);
                }
                else
                {
                    _logger.LogInformation("Coalition vote failed for Alliance {AllianceId}: {ApprovalPercentage}% approval, {ParticipationRate}% participation",
                        allianceId, approvalPercentage * 100, participationRate * 100);
                }

                return (votePassed, approvalPercentage, coalitionStatus);
            });
        }

        public async Task<Dictionary<string, object>> ManageCoalitionOperationAsync(string coalitionId, int kingdomId,
            string operationType, Dictionary<string, object> operationDetails)
        {
            _logger.LogInformation("Managing coalition operation: {CoalitionId}, Type: {OperationType}",
                coalitionId, operationType);

            return await _unitOfWork.ExecuteInTransactionAsync(async (unitOfWork) =>
            {
                var coalition = await GetActiveCoalition(coalitionId, kingdomId);
                if (coalition == null)
                {
                    return new Dictionary<string, object> { ["Error"] = "Active coalition not found" };
                }

                var operationResult = new Dictionary<string, object>
                {
                    ["CoalitionId"] = coalitionId,
                    ["OperationType"] = operationType,
                    ["OperationTimestamp"] = DateTime.UtcNow
                };

                switch (operationType.ToLower())
                {
                    case "joint_research":
                        operationResult = await ProcessCoalitionJointResearch(coalition, operationDetails, kingdomId);
                        break;

                    case "territory_coordination":
                        operationResult = await ProcessCoalitionTerritoryCoordination(coalition, operationDetails, kingdomId);
                        break;

                    case "kvk_preparation":
                        operationResult = await ProcessCoalitionKvKPreparation(coalition, operationDetails, kingdomId);
                        break;

                    case "resource_sharing":
                        operationResult = await ProcessCoalitionResourceSharing(coalition, operationDetails, kingdomId);
                        break;

                    case "strategic_planning":
                        operationResult = await ProcessCoalitionStrategicPlanning(coalition, operationDetails, kingdomId);
                        break;

                    default:
                        operationResult["Error"] = $"Unknown operation type: {operationType}";
                        break;
                }

                // Update coalition activity log
                await LogCoalitionActivity(coalitionId, kingdomId, operationType, operationResult);

                _logger.LogInformation("Coalition operation completed: {CoalitionId}, Type: {OperationType}",
                    coalitionId, operationType);

                return operationResult;
            });
        }

        public async Task<(bool Success, Dictionary<string, object> BenefitDistribution, List<int> AffectedAlliances)>
            DissolveCoalitionAsync(string coalitionId, int kingdomId, string dissolutionReason)
        {
            _logger.LogInformation("Dissolving coalition: {CoalitionId}, Reason: {Reason}",
                coalitionId, dissolutionReason);

            return await _unitOfWork.ExecuteInTransactionAsync(async (unitOfWork) =>
            {
                var coalition = await GetActiveCoalition(coalitionId, kingdomId);
                if (coalition == null)
                {
                    return (false, new Dictionary<string, object> { ["Error"] = "Coalition not found" }, new List<int>());
                }

                var memberAllianceIds = (List<int>)coalition["MemberAllianceIds"];
                var benefitDistribution = new Dictionary<string, object>();

                // Calculate accumulated coalition benefits
                var accumulatedBenefits = await CalculateAccumulatedCoalitionBenefits(coalitionId, kingdomId);

                // Distribute benefits fairly among member alliances
                foreach (var allianceId in memberAllianceIds)
                {
                    var alliance = await _allianceRepository.GetByIdAsync(allianceId, kingdomId);
                    if (alliance != null)
                    {
                        var allianceBenefits = CalculateAllianceShareOfCoalitionBenefits(
                            alliance, accumulatedBenefits, memberAllianceIds.Count);

                        await ApplyDissolutionBenefits(allianceId, kingdomId, allianceBenefits);
                        benefitDistribution[$"Alliance_{allianceId}"] = allianceBenefits;
                    }
                }

                // Mark coalition as dissolved
                await MarkCoalitionAsDissolved(coalitionId, kingdomId, dissolutionReason);

                // Restore individual alliance autonomy
                foreach (var allianceId in memberAllianceIds)
                {
                    await RestoreAllianceAutonomy(allianceId, kingdomId);
                }

                // Notify all member alliances
                foreach (var allianceId in memberAllianceIds)
                {
                    await NotifyAllianceOfDissolution(allianceId, kingdomId, dissolutionReason, benefitDistribution);
                }

                _logger.LogInformation("Coalition dissolved: {CoalitionId}, Affected alliances: {Count}",
                    coalitionId, memberAllianceIds.Count);

                return (true, benefitDistribution, memberAllianceIds);
            });
        }

        #endregion

        #region Communication & Coordination - Missing Interface Methods

        public async Task<(bool Success, Dictionary<string, object> DeliveryStatus, DateTime MessageTimestamp)>
            ProcessAllianceCommunicationAsync(int allianceId, int kingdomId, string communicationType,
                Dictionary<string, object> messageDetails, int senderPlayerId)
        {
            _logger.LogInformation("Processing alliance communication: Alliance {AllianceId}, Type: {CommunicationType}, Sender: {SenderId}",
                allianceId, communicationType, senderPlayerId);

            return await _unitOfWork.ExecuteInTransactionAsync(async (unitOfWork) =>
            {
                var alliance = await _allianceRepository.GetByIdAsync(allianceId, kingdomId);
                if (alliance == null)
                    throw new ArgumentException($"Alliance {allianceId} not found");

                var sender = await _playerRepository.GetByIdAsync(senderPlayerId, kingdomId);
                if (sender?.AllianceId != allianceId)
                {
                    return (false, new Dictionary<string, object>
                    {
                        ["Error"] = "Sender is not a member of the alliance"
                    }, DateTime.UtcNow);
                }

                var messageTimestamp = DateTime.UtcNow;
                var deliveryStatus = new Dictionary<string, object>
                {
                    ["MessageId"] = Guid.NewGuid().ToString(),
                    ["CommunicationType"] = communicationType,
                    ["SenderPlayerId"] = senderPlayerId,
                    ["AllianceId"] = allianceId,
                    ["MessageTimestamp"] = messageTimestamp,
                    ["Success"] = true
                };

                // Get alliance members for message delivery
                var members = await _playerRepository.GetAllianceMembersAsync(allianceId, kingdomId);
                deliveryStatus["DeliveredToMembers"] = members.Count();
                deliveryStatus["TotalMembers"] = members.Count();
                deliveryStatus["DeliveryRate"] = 1.0;

                return (true, deliveryStatus, messageTimestamp);
            });
        }

        public async Task<(bool Success, string EventId, Dictionary<string, object> ParticipantTracking, DateTime EventStartTime)>
            CoordinateAllianceEventAsync(int allianceId, int kingdomId, string eventType,
                Dictionary<string, object> eventDetails, int organizingPlayerId)
        {
            _logger.LogInformation("Coordinating alliance event: Alliance {AllianceId}, Type: {EventType}, Organizer: {OrganizerId}",
                allianceId, eventType, organizingPlayerId);

            return await _unitOfWork.ExecuteInTransactionAsync(async (unitOfWork) =>
            {
                var alliance = await _allianceRepository.GetByIdAsync(allianceId, kingdomId);
                if (alliance == null)
                    throw new ArgumentException($"Alliance {allianceId} not found");

                var organizer = await _playerRepository.GetByIdAsync(organizingPlayerId, kingdomId);
                if (organizer?.AllianceId != allianceId)
                {
                    return (false, "", new Dictionary<string, object>
                    {
                        ["Error"] = "Organizer is not a member of the alliance"
                    }, DateTime.UtcNow);
                }

                var eventId = $"ALLIANCE_EVENT_{allianceId}_{DateTime.UtcNow.Ticks}";
                var eventStartTime = DateTime.UtcNow.AddHours(1);

                var participantTracking = new Dictionary<string, object>
                {
                    ["EventId"] = eventId,
                    ["EventType"] = eventType,
                    ["OrganizingPlayerId"] = organizingPlayerId,
                    ["TotalMembers"] = alliance.MemberCount,
                    ["EstimatedParticipants"] = (int)(alliance.MemberCount * 0.7), // Estimate 70% participation
                    ["EventStartTime"] = eventStartTime
                };

                return (true, eventId, participantTracking, eventStartTime);
            });
        }

        public async Task<Dictionary<string, object>> ProcessIntelligenceSharingAsync(int allianceId, int kingdomId,
            string intelligenceType, Dictionary<string, object> intelligenceData, int sharingPlayerId)
        {
            _logger.LogInformation("Processing intelligence sharing: Alliance {AllianceId}, Type: {IntelligenceType}, Sharer: {SharerId}",
                allianceId, intelligenceType, sharingPlayerId);

            return await _unitOfWork.ExecuteInTransactionAsync(async (unitOfWork) =>
            {
                var alliance = await _allianceRepository.GetByIdAsync(allianceId, kingdomId);
                if (alliance == null)
                    throw new ArgumentException($"Alliance {allianceId} not found");

                var sharer = await _playerRepository.GetByIdAsync(sharingPlayerId, kingdomId);
                if (sharer?.AllianceId != allianceId)
                {
                    return new Dictionary<string, object>
                    {
                        ["Error"] = "Player is not a member of the alliance",
                        ["Success"] = false
                    };
                }

                var intelligenceId = Guid.NewGuid().ToString();
                var sharingResult = new Dictionary<string, object>
                {
                    ["IntelligenceId"] = intelligenceId,
                    ["IntelligenceType"] = intelligenceType,
                    ["SharingPlayerId"] = sharingPlayerId,
                    ["AllianceId"] = allianceId,
                    ["SharedAt"] = DateTime.UtcNow,
                    ["Success"] = true,
                    ["MembersNotified"] = alliance.MemberCount
                };

                return sharingResult;
            });
        }

        #endregion

        #region Alliance Progression & Leveling - Missing Interface Methods

        public async Task<(bool LevelUp, int NewLevel, Dictionary<string, object> UnlockedFeatures,
               Dictionary<string, int> CapacityIncreases)>
            ProcessAllianceExperienceAsync(int allianceId, int kingdomId, long experienceGained, string experienceSource)
        {
            _logger.LogInformation("Processing alliance experience: Alliance {AllianceId}, XP: {ExperienceGained}, Source: {Source}",
                allianceId, experienceGained, experienceSource);

            return await _unitOfWork.ExecuteInTransactionAsync(async (unitOfWork) =>
            {
                var alliance = await _allianceRepository.GetByIdAsync(allianceId, kingdomId);
                if (alliance == null)
                    throw new ArgumentException($"Alliance {allianceId} not found");

                var currentLevel = alliance.Level;
                var currentExperience = alliance.ExperiencePoints;
                var newExperience = currentExperience + experienceGained;

                // Calculate level progression
                var newLevel = CalculateAllianceLevelFromExperience(newExperience);
                var levelUp = newLevel > currentLevel;

                var unlockedFeatures = new Dictionary<string, object>();
                var capacityIncreases = new Dictionary<string, int>();

                if (levelUp)
                {
                    unlockedFeatures = GetUnlockedFeaturesForLevel(newLevel);
                    capacityIncreases = GetCapacityIncreasesForLevel(newLevel);

                    // Update alliance level and experience - Fixed with kingdomId parameter
                    alliance.Level = newLevel;
                    alliance.ExperiencePoints = newExperience;
                    await _allianceRepository.UpdateAsync(alliance, kingdomId);
                }
                else
                {
                    // Just update experience - Fixed with kingdomId parameter
                    alliance.ExperiencePoints = newExperience;
                    await _allianceRepository.UpdateAsync(alliance, kingdomId);
                }

                _logger.LogInformation("Alliance experience processed: Alliance {AllianceId}, Level: {CurrentLevel}->{NewLevel}, XP: {NewExperience}",
                    allianceId, currentLevel, newLevel, newExperience);

                return (levelUp, newLevel, unlockedFeatures, capacityIncreases);
            });
        }

        public async Task<(long TotalPower, Dictionary<string, long> PowerBreakdown)> CalculateAlliancePowerAsync(int allianceId,
            int kingdomId)
        {
            var alliance = await _allianceRepository.GetByIdAsync(allianceId, kingdomId);
            if (alliance == null)
                throw new ArgumentException($"Alliance {allianceId} not found");

            var members = await _playerRepository.GetAllianceMembersAsync(allianceId, kingdomId);

            var powerBreakdown = new Dictionary<string, long>
            {
                // Fixed: Use Power instead of TotalPower
                ["MemberPower"] = members.Sum(m => m.Power),
                ["ResearchBonus"] = CalculateResearchPowerBonus(alliance),
                ["TerritoryBonus"] = await CalculateTerritoryPowerBonus(allianceId, kingdomId),
                ["LevelBonus"] = alliance.Level * 1000,
                ["AchievementBonus"] = await CalculateAchievementPowerBonus(allianceId, kingdomId)
            };

            var totalPower = powerBreakdown.Values.Sum();

            return (totalPower, powerBreakdown);
        }

        public async Task<(bool NewAchievement, List<string> UnlockedAchievements, Dictionary<string, object> Rewards)>
            ProcessAllianceAchievementAsync(int allianceId, int kingdomId, string achievementType,
                Dictionary<string, object> achievementData)
        {
            _logger.LogInformation("Processing alliance achievement: Alliance {AllianceId}, Type: {AchievementType}",
                allianceId, achievementType);

            return await _unitOfWork.ExecuteInTransactionAsync(async (unitOfWork) =>
            {
                var alliance = await _allianceRepository.GetByIdAsync(allianceId, kingdomId);
                if (alliance == null)
                    throw new ArgumentException($"Alliance {allianceId} not found");

                // Get current achievements (placeholder - would need actual field in Alliance model)
                var currentAchievements = await GetAllianceAchievements(allianceId, kingdomId);
                var newAchievements = CheckForNewAchievements(achievementType, achievementData, currentAchievements);

                var hasNewAchievement = newAchievements.Any();
                var rewards = new Dictionary<string, object>();

                if (hasNewAchievement)
                {
                    rewards = CalculateAchievementRewards(newAchievements, alliance.Level);
                    await ApplyAchievementRewards(allianceId, kingdomId, rewards);

                    // Update alliance achievements
                    var updatedAchievements = currentAchievements.Concat(newAchievements).ToList();
                    await UpdateAllianceAchievements(allianceId, kingdomId, updatedAchievements);
                }

                return (hasNewAchievement, newAchievements, rewards);
            });
        }

        #endregion

        #region KvK Event Integration - Missing Interface Methods

        public async Task<(bool Success, Dictionary<string, object> RoleAssignments, Dictionary<string, object> Objectives,
               Dictionary<string, object> RewardStructure)>
            IntegrateKvKParticipationAsync(int allianceId, int kingdomId, string kvkEventId, string participationLevel)
        {
            _logger.LogInformation("Integrating KvK participation: Alliance {AllianceId}, Event: {KvKEventId}, Level: {ParticipationLevel}",
                allianceId, kvkEventId, participationLevel);

            return await _unitOfWork.ExecuteInTransactionAsync(async (unitOfWork) =>
            {
                var alliance = await _allianceRepository.GetByIdAsync(allianceId, kingdomId);
                if (alliance == null)
                    throw new ArgumentException($"Alliance {allianceId} not found");

                var roleAssignments = GenerateKvKRoleAssignments(alliance, participationLevel);
                var objectives = GenerateKvKObjectives(alliance, kvkEventId, participationLevel);
                var rewardStructure = GenerateKvKRewardStructure(alliance, participationLevel);

                // Store KvK participation record
                await StoreKvKParticipation(allianceId, kingdomId, kvkEventId, new Dictionary<string, object>
                {
                    ["ParticipationLevel"] = participationLevel,
                    ["RoleAssignments"] = roleAssignments,
                    ["Objectives"] = objectives,
                    ["RewardStructure"] = rewardStructure,
                    ["IntegratedAt"] = DateTime.UtcNow
                });

                return (true, roleAssignments, objectives, rewardStructure);
            });
        }

        public async Task<Dictionary<string, object>> CoordinateKvKOperationsAsync(string coalitionId, int kingdomId,
            string operationType, Dictionary<string, object> operationDetails)
        {
            _logger.LogInformation("Coordinating KvK operations: Coalition {CoalitionId}, Type: {OperationType}",
                coalitionId, operationType);

            return await _unitOfWork.ExecuteInTransactionAsync(async (unitOfWork) =>
            {
                var coalition = await GetActiveCoalition(coalitionId, kingdomId);
                if (coalition == null)
                {
                    return new Dictionary<string, object> { ["Error"] = "Active coalition not found" };
                }

                var coordinationResult = new Dictionary<string, object>
                {
                    ["CoalitionId"] = coalitionId,
                    ["OperationType"] = operationType,
                    ["CoordinationTimestamp"] = DateTime.UtcNow,
                    ["ParticipatingAlliances"] = ((List<int>)coalition["MemberAllianceIds"]).Count
                };

                // Process specific KvK operation types
                switch (operationType.ToLower())
                {
                    case "coordinated_attack":
                        coordinationResult = await ProcessCoordinatedAttack(coalition, operationDetails, kingdomId);
                        break;
                    case "defensive_positioning":
                        coordinationResult = await ProcessDefensivePositioning(coalition, operationDetails, kingdomId);
                        break;
                    case "resource_pooling":
                        coordinationResult = await ProcessKvKResourcePooling(coalition, operationDetails, kingdomId);
                        break;
                    default:
                        coordinationResult["Error"] = $"Unknown KvK operation type: {operationType}";
                        break;
                }

                return coordinationResult;
            });
        }

        #endregion

        #region Anti-Exploitation & Balance - Missing Interface Methods

        public async Task<(bool SuspiciousActivity, List<string> RiskFactors, Dictionary<string, object> RecommendedActions)>
            MonitorAllianceExploitationAsync(int allianceId, int kingdomId, int monitoringPeriodDays = 7)
        {
            var alliance = await _allianceRepository.GetByIdAsync(allianceId, kingdomId);
            if (alliance == null)
                throw new ArgumentException($"Alliance {allianceId} not found");

            var riskFactors = new List<string>();
            var recommendedActions = new Dictionary<string, object>();

            // Monitor for suspicious patterns
            var suspiciousActivity = await DetectSuspiciousPatterns(allianceId, kingdomId, monitoringPeriodDays);

            if (suspiciousActivity.HasSuspiciousActivity)
            {
                riskFactors.AddRange(suspiciousActivity.RiskFactors);
                recommendedActions = GenerateExploitationRecommendations(suspiciousActivity.RiskFactors);
            }

            _logger.LogInformation("Alliance exploitation monitoring: Alliance {AllianceId}, Suspicious: {SuspiciousActivity}, Risk factors: {RiskCount}",
                allianceId, suspiciousActivity.HasSuspiciousActivity, riskFactors.Count);

            return (suspiciousActivity.HasSuspiciousActivity, riskFactors, recommendedActions);
        }

        public async Task<(bool IsValid, List<string> ValidationWarnings, Dictionary<string, object> AppliedRestrictions)>
            ValidateAllianceOperationAsync(int allianceId, int kingdomId, string operationType,
                Dictionary<string, object> operationDetails)
        {
            var alliance = await _allianceRepository.GetByIdAsync(allianceId, kingdomId);
            if (alliance == null)
                throw new ArgumentException($"Alliance {allianceId} not found");

            var validationWarnings = new List<string>();
            var appliedRestrictions = new Dictionary<string, object>();
            var isValid = true;

            // Validate operation against exploitation rules
            var validation = await ValidateOperationLegitimacy(allianceId, kingdomId, operationType, operationDetails);

            if (!validation.IsLegitimate)
            {
                isValid = false;
                validationWarnings.AddRange(validation.Warnings);
                appliedRestrictions = validation.Restrictions;
            }

            return (isValid, validationWarnings, appliedRestrictions);
        }

        public async Task<Dictionary<string, object>> ValidateSkillBasedAlternativesAsync(int allianceId, int kingdomId,
            string featureType)
        {
            var alliance = await _allianceRepository.GetByIdAsync(allianceId, kingdomId);
            if (alliance == null)
                throw new ArgumentException($"Alliance {allianceId} not found");

            var alternatives = new Dictionary<string, object>
            {
                ["FeatureType"] = featureType,
                ["AllianceId"] = allianceId,
                ["SkillBasedAlternatives"] = GetSkillBasedAlternatives(featureType),
                ["EffectivenessComparison"] = CalculateAlternativeEffectiveness(featureType),
                ["ValidationTimestamp"] = DateTime.UtcNow
            };

            return alternatives;
        }

        #endregion

        #region Alliance Information & Analytics - Missing Interface Methods

        public async Task<Dictionary<string, object>> GetAllianceProfileAsync(int allianceId, int kingdomId,
            bool includePrivateData = false, int? requestingPlayerId = null)
        {
            var alliance = await _allianceRepository.GetByIdAsync(allianceId, kingdomId);
            if (alliance == null)
                throw new ArgumentException($"Alliance {allianceId} not found");

            var profile = new Dictionary<string, object>
            {
                ["AllianceId"] = allianceId,
                ["Name"] = alliance.Name,
                ["Level"] = alliance.Level,
                ["MemberCount"] = alliance.MemberCount,
                // Fixed: Use Power instead of TotalPower
                ["TotalPower"] = alliance.Power,
                ["CreatedAt"] = alliance.CreatedAt,
                // Fixed: Use IsOpenToJoin instead of IsRecruiting
                ["IsRecruiting"] = alliance.IsOpenToJoin,
                ["Description"] = alliance.Description
            };

            if (includePrivateData && requestingPlayerId.HasValue)
            {
                var requester = await _playerRepository.GetByIdAsync(requestingPlayerId.Value, kingdomId);
                if (requester?.AllianceId == allianceId)
                {
                    // Fixed: Create research levels dictionary from individual properties
                    profile["ResearchLevels"] = CreateResearchLevelsDictionary(alliance);
                    profile["Treasury"] = await GetAllianceTreasuryBalance(allianceId, kingdomId);
                    profile["Territories"] = await GetAllianceTerritories(allianceId, kingdomId);
                }
            }

            return profile;
        }

        public async Task<Dictionary<string, object>> GetAllianceRankingsAsync(int allianceId, int kingdomId)
        {
            var alliance = await _allianceRepository.GetByIdAsync(allianceId, kingdomId);
            if (alliance == null)
                throw new ArgumentException($"Alliance {allianceId} not found");

            var rankings = new Dictionary<string, object>
            {
                ["AllianceId"] = allianceId,
                ["PowerRanking"] = await GetAlliancePowerRanking(allianceId, kingdomId),
                ["MemberCountRanking"] = await GetAllianceMemberRanking(allianceId, kingdomId),
                ["ResearchRanking"] = await GetAllianceResearchRanking(allianceId, kingdomId),
                ["TerritoryRanking"] = await GetAllianceTerritoryRanking(allianceId, kingdomId),
                ["RankingsGeneratedAt"] = DateTime.UtcNow
            };

            return rankings;
        }

        public async Task<Dictionary<string, object>> AnalyzeAlliancePerformanceAsync(int allianceId, int kingdomId,
            string analysisType, int timeframeDays = 30)
        {
            var alliance = await _allianceRepository.GetByIdAsync(allianceId, kingdomId);
            if (alliance == null)
                throw new ArgumentException($"Alliance {allianceId} not found");

            var analysis = new Dictionary<string, object>
            {
                ["AllianceId"] = allianceId,
                ["AnalysisType"] = analysisType,
                ["TimeframeDays"] = timeframeDays,
                ["AnalysisTimestamp"] = DateTime.UtcNow
            };

            switch (analysisType.ToLower())
            {
                case "growth":
                    analysis["GrowthMetrics"] = await AnalyzeGrowthMetrics(allianceId, kingdomId, timeframeDays);
                    break;
                case "activity":
                    analysis["ActivityMetrics"] = await AnalyzeActivityMetrics(allianceId, kingdomId, timeframeDays);
                    break;
                case "combat":
                    analysis["CombatMetrics"] = await AnalyzeCombatMetrics(allianceId, kingdomId, timeframeDays);
                    break;
                case "research":
                    analysis["ResearchMetrics"] = await AnalyzeResearchMetrics(allianceId, kingdomId, timeframeDays);
                    break;
                default:
                    analysis["Error"] = $"Unknown analysis type: {analysisType}";
                    break;
            }

            return analysis;
        }

        #endregion

        #region Research Trees & Collective Benefits (Existing methods - fixed)

        public async Task<(bool Success, int NewResearchLevel, Dictionary<string, object> UnlockedBenefits,
               Dictionary<int, long> ContributionTracking)>
            ProcessAllianceResearchAsync(int allianceId, int kingdomId, string researchType, string researchNode,
                Dictionary<int, Dictionary<string, long>> memberContributions)
        {
            _logger.LogInformation("Processing alliance research: Alliance {AllianceId}, Type: {ResearchType}, Node: {ResearchNode}",
                allianceId, researchType, researchNode);

            return await _unitOfWork.ExecuteInTransactionAsync(async (unitOfWork) =>
            {
                var alliance = await _allianceRepository.GetByIdAsync(allianceId, kingdomId);
                if (alliance == null)
                    throw new ArgumentException($"Alliance {allianceId} not found");

                // Validate research prerequisites
                var (canResearch, prerequisites, requiredContributions, estimatedBenefits) =
                    await ValidateResearchRequirementsAsync(allianceId, kingdomId, researchType, researchNode);

                if (!canResearch)
                {
                    return (false, 0, new Dictionary<string, object>
                    {
                        ["Error"] = string.Join("; ", prerequisites)
                    }, new Dictionary<int, long>());
                }

                // Validate member contributions and process
                var contributionTracking = new Dictionary<int, long>();
                foreach (var memberContribution in memberContributions)
                {
                    var playerId = memberContribution.Key;
                    var resources = memberContribution.Value;

                    var player = await _playerRepository.GetByIdAsync(playerId, kingdomId);
                    if (player?.AllianceId != allianceId)
                    {
                        return (false, 0, new Dictionary<string, object>
                        {
                            ["Error"] = $"Player {playerId} is not a member of alliance {allianceId}"
                        }, new Dictionary<int, long>());
                    }

                    var contributionValue = resources.Values.Sum();
                    contributionTracking[playerId] = contributionValue;
                }

                // Get current research level from alliance properties
                var currentLevel = GetAllianceResearchLevel(alliance, researchType, researchNode);
                var newLevel = Math.Min(currentLevel + 1, MAX_RESEARCH_LEVEL);

                // Update alliance research level
                await UpdateAllianceResearchLevel(allianceId, kingdomId, researchType, researchNode, newLevel);

                var unlockedBenefits = CalculateResearchBenefits(researchType, researchNode, newLevel);

                _logger.LogInformation("Alliance research completed: Alliance {AllianceId}, {ResearchType}.{ResearchNode} Level {NewLevel}",
                    allianceId, researchType, researchNode, newLevel);

                return (true, newLevel, unlockedBenefits, contributionTracking);
            });
        }

        public async Task<Dictionary<string, object>> ApplyCollectiveResearchBenefitsAsync(int allianceId, int kingdomId)
        {
            var alliance = await _allianceRepository.GetByIdAsync(allianceId, kingdomId);
            if (alliance == null)
                throw new ArgumentException($"Alliance {allianceId} not found");

            var members = await _playerRepository.GetAllianceMembersAsync(allianceId, kingdomId);

            var appliedBenefits = new Dictionary<string, object>
            {
                ["MilitaryBranch"] = new Dictionary<string, object>
                {
                    ["AttackBonus"] = alliance.MilitaryAttackBonus,
                    ["DefenseBonus"] = alliance.MilitaryDefenseBonus,
                    ["HealthBonus"] = alliance.MilitaryHealthBonus,
                    ["SpeedBonus"] = alliance.MilitarySpeedBonus,
                    ["CapacityBonus"] = alliance.MilitaryCapacityBonus
                },
                ["EconomicBranch"] = new Dictionary<string, object>
                {
                    ["GatheringBonus"] = alliance.EconomicGatheringBonus,
                    ["StorageBonus"] = alliance.EconomicStorageBonus,
                    ["TradeBonus"] = alliance.EconomicTradeBonus,
                    ["ProductionBonus"] = alliance.EconomicProductionBonus
                },
                ["TechnologyBranch"] = new Dictionary<string, object>
                {
                    ["ConstructionBonus"] = alliance.TechnologyConstructionBonus,
                    ["UpgradeBonus"] = alliance.TechnologyUpgradeBonus,
                    ["TrainingBonus"] = alliance.TechnologyTrainingBonus,
                    ["HealingBonus"] = alliance.TechnologyHealingBonus
                },
                ["MembersAffected"] = members.Count(),
                ["BenefitsAppliedAt"] = DateTime.UtcNow
            };

            return appliedBenefits;
        }

        public async Task<(bool CanResearch, List<string> Prerequisites, Dictionary<string, long> RequiredContributions,
               Dictionary<string, object> EstimatedBenefits)>
            ValidateResearchRequirementsAsync(int allianceId, int kingdomId, string researchType, string researchNode)
        {
            var alliance = await _allianceRepository.GetByIdAsync(allianceId, kingdomId);
            if (alliance == null)
                return (false, new List<string> { "Alliance not found" }, new Dictionary<string, long>(),
                       new Dictionary<string, object>());

            var prerequisites = new List<string>();
            var currentLevel = GetAllianceResearchLevel(alliance, researchType, researchNode);
            var targetLevel = currentLevel + 1;

            if (targetLevel > MAX_RESEARCH_LEVEL)
            {
                prerequisites.Add($"Maximum research level reached ({MAX_RESEARCH_LEVEL})");
            }

            if (alliance.Level < GetRequiredAllianceLevelForResearch(researchType, researchNode, targetLevel))
            {
                prerequisites.Add($"Alliance level {GetRequiredAllianceLevelForResearch(researchType, researchNode, targetLevel)} required");
            }

            var requiredContributions = CalculateResearchResourceRequirements(researchType, researchNode, targetLevel);
            var estimatedBenefits = CalculateResearchBenefits(researchType, researchNode, targetLevel);

            return (prerequisites.Count == 0, prerequisites, requiredContributions, estimatedBenefits);
        }

        public async Task<Dictionary<string, object>> TrackResearchContributionsAsync(int allianceId, int kingdomId,
            int timeframeDays = 30)
        {
            var members = await _playerRepository.GetAllianceMembersAsync(allianceId, kingdomId);
            var contributionRecords = await GetMemberContributionRecords(allianceId, kingdomId, timeframeDays);

            var memberContributions = new Dictionary<string, object>();
            var totalContributions = 0L;

            foreach (var member in members)
            {
                var memberRecord = contributionRecords.GetValueOrDefault(member.Id, new Dictionary<string, long>());
                var memberTotal = memberRecord.Values.Sum();
                totalContributions += memberTotal;

                memberContributions[$"Player_{member.Id}"] = new Dictionary<string, object>
                {
                    // Fixed: Use Name instead of PlayerName
                    ["PlayerName"] = member.Name,
                    ["TotalContribution"] = memberTotal,
                    ["ResourceBreakdown"] = memberRecord,
                    ["ContributionPercentage"] = 0.0
                };
            }

            // Calculate percentages
            foreach (var memberKey in memberContributions.Keys.ToList())
            {
                var memberData = (Dictionary<string, object>)memberContributions[memberKey];
                var memberTotal = (long)memberData["TotalContribution"];
                var percentage = totalContributions > 0 ? (double)memberTotal / totalContributions * 100.0 : 0.0;
                memberData["ContributionPercentage"] = percentage;
            }

            return new Dictionary<string, object>
            {
                ["TimeframeDays"] = timeframeDays,
                ["TotalContributions"] = totalContributions,
                ["MemberContributions"] = memberContributions
            };
        }

        #endregion

        #region Member Management & Social Systems (Fixed existing methods)

        public async Task<(bool Success, string MembershipStatus, Dictionary<string, object> IntegrationPlan,
               DateTime ProbationEndDate)>
            ProcessMembershipAsync(int allianceId, int playerId, int kingdomId, bool isInvitation,
                Dictionary<string, object> applicantDetails)
        {
            _logger.LogInformation("Processing membership: Alliance {AllianceId}, Player {PlayerId}, Invitation: {IsInvitation}",
                allianceId, playerId, isInvitation);

            return await _unitOfWork.ExecuteInTransactionAsync(async (unitOfWork) =>
            {
                var alliance = await _allianceRepository.GetByIdAsync(allianceId, kingdomId);
                if (alliance == null)
                    throw new ArgumentException($"Alliance {allianceId} not found");

                var player = await _playerRepository.GetByIdAsync(playerId, kingdomId);
                if (player == null)
                    throw new ArgumentException($"Player {playerId} not found");

                if (player.AllianceId.HasValue)
                {
                    return (false, "Already_In_Alliance", new Dictionary<string, object>
                    {
                        ["Error"] = "Player is already in an alliance"
                    }, DateTime.UtcNow);
                }

                if (alliance.MemberCount >= MAX_ALLIANCE_SIZE)
                {
                    return (false, "Alliance_Full", new Dictionary<string, object>
                    {
                        ["Error"] = $"Alliance is at maximum capacity ({MAX_ALLIANCE_SIZE} members)"
                    }, DateTime.UtcNow);
                }

                var membershipStatus = isInvitation ? "Full_Member" : "Probationary_Member";
                var probationEndDate = isInvitation ? DateTime.UtcNow : DateTime.UtcNow.AddDays(7);

                var integrationPlan = new Dictionary<string, object>
                {
                    ["WelcomeMessage"] = $"Welcome to {alliance.Name}!",
                    ["AssignedRole"] = isInvitation ? "Member" : "Recruit",
                    ["InitialTasks"] = GetNewMemberTasks(membershipStatus),
                    ["AccessibleFeatures"] = GetMemberAccessibleFeatures(membershipStatus)
                };

                // Fixed: Update player alliance with kingdomId parameter
                player.AllianceId = allianceId;
                await _playerRepository.UpdateAsync(player, kingdomId);

                return (true, membershipStatus, integrationPlan, probationEndDate);
            });
        }

        public async Task<Dictionary<string, object>> MonitorMemberActivityAsync(int allianceId, int kingdomId,
            int timeframeDays = 7)
        {
            var alliance = await _allianceRepository.GetByIdAsync(allianceId, kingdomId);
            if (alliance == null)
                throw new ArgumentException($"Alliance {allianceId} not found");

            var members = await _playerRepository.GetAllianceMembersAsync(allianceId, kingdomId);

            // Fixed: Use LastActiveAt instead of LastLogin
            var activeMembers = members.Count(m => m.LastActiveAt > DateTime.UtcNow.AddDays(-timeframeDays));

            return new Dictionary<string, object>
            {
                ["AllianceId"] = allianceId,
                ["MonitoringPeriod"] = timeframeDays,
                ["TotalMembers"] = members.Count(),
                ["ActiveMembers"] = activeMembers,
                ["ReportGeneratedAt"] = DateTime.UtcNow
            };
        }

        public async Task<(bool Success, Dictionary<string, object> BenefitsRemoved, bool TerritoryEviction,
               Dictionary<string, object> TransitionPlan)>
            ProcessMemberRemovalAsync(int allianceId, int playerId, int kingdomId, string removalReason,
                int authorizingPlayerId)
        {
            _logger.LogInformation("Processing member removal: Alliance {AllianceId}, Player {PlayerId}, Reason: {RemovalReason}",
                allianceId, playerId, removalReason);

            return await _unitOfWork.ExecuteInTransactionAsync(async (unitOfWork) =>
            {
                var alliance = await _allianceRepository.GetByIdAsync(allianceId, kingdomId);
                if (alliance == null)
                    throw new ArgumentException($"Alliance {allianceId} not found");

                var player = await _playerRepository.GetByIdAsync(playerId, kingdomId);
                if (player?.AllianceId != allianceId)
                {
                    return (false, new Dictionary<string, object> { ["Error"] = "Player not in alliance" },
                           false, new Dictionary<string, object>());
                }

                var benefitsRemoved = new Dictionary<string, object>
                {
                    ["ResearchBonuses"] = "All alliance research bonuses removed",
                    ["TreasuryAccess"] = "Treasury access revoked"
                };

                var transitionPlan = new Dictionary<string, object>
                {
                    ["GracePeriod"] = removalReason == "Voluntary" ? TimeSpan.FromHours(24) : TimeSpan.FromHours(2),
                    ["AllianceChatAccess"] = TimeSpan.FromHours(1),
                    ["ReapplicationCooldown"] = TimeSpan.FromDays(7)
                };

                // Fixed: Update player alliance with kingdomId parameter
                player.AllianceId = null;
                await _playerRepository.UpdateAsync(player, kingdomId);

                return (true, benefitsRemoved, false, transitionPlan);
            });
        }

        public async Task<(bool Success, Dictionary<string, object> TransactionDetails, DateTime TransferCompletionTime)>
            ProcessMemberResourceTradingAsync(int senderPlayerId, int receiverPlayerId, int allianceId, int kingdomId,
                Dictionary<string, long> resourceTransfer)
        {
            _logger.LogInformation("Processing member resource trading: Sender {SenderId} → Receiver {ReceiverId}",
                senderPlayerId, receiverPlayerId);

            return await _unitOfWork.ExecuteInTransactionAsync(async (unitOfWork) =>
            {
                var sender = await _playerRepository.GetByIdAsync(senderPlayerId, kingdomId);
                var receiver = await _playerRepository.GetByIdAsync(receiverPlayerId, kingdomId);

                if (sender?.AllianceId != allianceId || receiver?.AllianceId != allianceId)
                {
                    return (false, new Dictionary<string, object>
                    {
                        ["Error"] = "Both players must be in the same alliance for trading"
                    }, DateTime.UtcNow);
                }

                var transactionDetails = new Dictionary<string, object>
                {
                    ["TransactionId"] = Guid.NewGuid().ToString(),
                    ["SenderPlayerId"] = senderPlayerId,
                    ["ReceiverPlayerId"] = receiverPlayerId,
                    ["ResourceTransfer"] = resourceTransfer,
                    ["TransactionStatus"] = "Completed",
                    ["CompletedAt"] = DateTime.UtcNow
                };

                return (true, transactionDetails, DateTime.UtcNow.AddMinutes(30));
            });
        }

        #endregion

        #region Private Helper Methods (Fixed to match actual entity properties)

        private async Task<List<Player>> GetAllianceActiveMembers(int allianceId, int kingdomId)
        {
            var members = await _playerRepository.GetAllianceMembersAsync(allianceId, kingdomId);
            // Fixed: Use LastActiveAt instead of LastLogin
            return members.Where(m => m.LastActiveAt > DateTime.UtcNow.AddDays(-7)).ToList();
        }

        private Dictionary<string, int> CreateResearchLevelsDictionary(Alliance alliance)
        {
            return new Dictionary<string, int>
            {
                ["MilitaryAttack"] = alliance.MilitaryAttackResearch,
                ["MilitaryDefense"] = alliance.MilitaryDefenseResearch,
                ["MilitaryHealth"] = alliance.MilitaryHealthResearch,
                ["MilitarySpeed"] = alliance.MilitarySpeedResearch,
                ["MilitaryCapacity"] = alliance.MilitaryCapacityResearch,
                ["EconomicGathering"] = alliance.EconomicGatheringResearch,
                ["EconomicStorage"] = alliance.EconomicStorageResearch,
                ["EconomicTrade"] = alliance.EconomicTradeResearch,
                ["EconomicProduction"] = alliance.EconomicProductionResearch,
                ["EconomicTaxation"] = alliance.EconomicTaxationResearch,
                ["TechnologyConstruction"] = alliance.TechnologyConstructionResearch,
                ["TechnologyUpgrade"] = alliance.TechnologyUpgradeResearch,
                ["TechnologyTraining"] = alliance.TechnologyTrainingResearch,
                ["TechnologyResearch"] = alliance.TechnologyResearchResearch,
                ["TechnologyHealing"] = alliance.TechnologyHealingResearch
            };
        }

        private int GetAllianceResearchLevel(Alliance alliance, string researchType, string researchNode)
        {
            var key = $"{researchType}{researchNode}";
            return key.ToLower() switch
            {
                "militaryattack" => alliance.MilitaryAttackResearch,
                "militarydefense" => alliance.MilitaryDefenseResearch,
                "militaryhealth" => alliance.MilitaryHealthResearch,
                "militaryspeed" => alliance.MilitarySpeedResearch,
                "militarycapacity" => alliance.MilitaryCapacityResearch,
                "economicgathering" => alliance.EconomicGatheringResearch,
                "economicstorage" => alliance.EconomicStorageResearch,
                "economictrade" => alliance.EconomicTradeResearch,
                "economicproduction" => alliance.EconomicProductionResearch,
                "economictaxation" => alliance.EconomicTaxationResearch,
                "technologyconstruction" => alliance.TechnologyConstructionResearch,
                "technologyupgrade" => alliance.TechnologyUpgradeResearch,
                "technologytraining" => alliance.TechnologyTrainingResearch,
                "technologyresearch" => alliance.TechnologyResearchResearch,
                "technologyhealing" => alliance.TechnologyHealingResearch,
                _ => 0
            };
        }

        private long CalculateResearchPowerBonus(Alliance alliance)
        {
            var totalResearchLevels = alliance.MilitaryAttackResearch + alliance.MilitaryDefenseResearch +
                                    alliance.EconomicGatheringResearch + alliance.TechnologyConstructionResearch;
            return totalResearchLevels * 1000;
        }

        // Additional helper method stubs - implementing as placeholders for compilation
        private async Task StoreCoalitionProposal(string coalitionId, Dictionary<string, object> proposal, int kingdomId) { }
        private async Task NotifyAllianceOfCoalitionProposal(int allianceId, int kingdomId, Dictionary<string, object> proposal) { }
        private async Task<Dictionary<string, object>> GetCoalitionProposal(string coalitionId, int kingdomId) => new Dictionary<string, object>();
        private async Task StoreCoalitionVotingResults(string coalitionId, int allianceId, int kingdomId, Dictionary<string, object> results) { }
        private async Task<Dictionary<string, object>> GetActiveCoalition(string coalitionId, int kingdomId) => new Dictionary<string, object> { ["MemberAllianceIds"] = new List<int>() };
        private int CalculateAllianceLevelFromExperience(long experience) => (int)(Math.Sqrt(experience / 1000) + 1);
        private Dictionary<string, object> GetUnlockedFeaturesForLevel(int level) => new Dictionary<string, object>();
        private Dictionary<string, int> GetCapacityIncreasesForLevel(int level) => new Dictionary<string, int>();
        private async Task<long> CalculateTerritoryPowerBonus(int allianceId, int kingdomId) => 50000;
        private async Task<long> CalculateAchievementPowerBonus(int allianceId, int kingdomId) => 25000;
        private async Task<List<string>> GetAllianceAchievements(int allianceId, int kingdomId) => new List<string>();
        private List<string> CheckForNewAchievements(string type, Dictionary<string, object> data, List<string> current) => new List<string>();
        private Dictionary<string, object> CalculateAchievementRewards(List<string> achievements, int level) => new Dictionary<string, object>();
        private async Task ApplyAchievementRewards(int allianceId, int kingdomId, Dictionary<string, object> rewards) { }
        private async Task UpdateAllianceAchievements(int allianceId, int kingdomId, List<string> achievements) { }
        private Dictionary<string, object> GenerateKvKRoleAssignments(Alliance alliance, string level) => new Dictionary<string, object>();
        private Dictionary<string, object> GenerateKvKObjectives(Alliance alliance, string eventId, string level) => new Dictionary<string, object>();
        private Dictionary<string, object> GenerateKvKRewardStructure(Alliance alliance, string level) => new Dictionary<string, object>();
        private async Task StoreKvKParticipation(int allianceId, int kingdomId, string eventId, Dictionary<string, object> data) { }
        private async Task<(bool HasSuspiciousActivity, List<string> RiskFactors)> DetectSuspiciousPatterns(int allianceId, int kingdomId, int days) => (false, new List<string>());
        private Dictionary<string, object> GenerateExploitationRecommendations(List<string> riskFactors) => new Dictionary<string, object>();
        private async Task<(bool IsLegitimate, List<string> Warnings, Dictionary<string, object> Restrictions)> ValidateOperationLegitimacy(int allianceId, int kingdomId, string type, Dictionary<string, object> details) => (true, new List<string>(), new Dictionary<string, object>());
        private Dictionary<string, object> GetSkillBasedAlternatives(string featureType) => new Dictionary<string, object>();
        private Dictionary<string, object> CalculateAlternativeEffectiveness(string featureType) => new Dictionary<string, object>();
        private async Task<Dictionary<string, long>> GetAllianceTreasuryBalance(int allianceId, int kingdomId) => new Dictionary<string, long>();
        private async Task<List<object>> GetAllianceTerritories(int allianceId, int kingdomId) => new List<object>();
        private async Task<int> GetAlliancePowerRanking(int allianceId, int kingdomId) => 1;
        private async Task<int> GetAllianceMemberRanking(int allianceId, int kingdomId) => 1;
        private async Task<int> GetAllianceResearchRanking(int allianceId, int kingdomId) => 1;
        private async Task<int> GetAllianceTerritoryRanking(int allianceId, int kingdomId) => 1;
        private async Task<Dictionary<string, object>> AnalyzeGrowthMetrics(int allianceId, int kingdomId, int days) => new Dictionary<string, object>();
        private async Task<Dictionary<string, object>> AnalyzeActivityMetrics(int allianceId, int kingdomId, int days) => new Dictionary<string, object>();
        private async Task<Dictionary<string, object>> AnalyzeCombatMetrics(int allianceId, int kingdomId, int days) => new Dictionary<string, object>();
        private async Task<Dictionary<string, object>> AnalyzeResearchMetrics(int allianceId, int kingdomId, int days) => new Dictionary<string, object>();
        private async Task UpdateAllianceResearchLevel(int allianceId, int kingdomId, string researchType, string researchNode, int newLevel) { }
        private Dictionary<string, object> CalculateResearchBenefits(string researchType, string researchNode, int level) => new Dictionary<string, object>();
        private int GetRequiredAllianceLevelForResearch(string researchType, string researchNode, int targetLevel) => targetLevel / 5 + 1;
        private Dictionary<string, long> CalculateResearchResourceRequirements(string researchType, string researchNode, int level) => new Dictionary<string, long> { ["Food"] = level * 10000, ["Wood"] = level * 8000, ["Iron"] = level * 6000 };
        private async Task<Dictionary<int, Dictionary<string, long>>> GetMemberContributionRecords(int allianceId, int kingdomId, int days) => new Dictionary<int, Dictionary<string, long>>();
        private List<object> GetNewMemberTasks(string status) => new List<object>();
        private List<object> GetMemberAccessibleFeatures(string status) => new List<object>();

        // All other helper method stubs for compilation
        private async Task LogCoalitionActivity(string coalitionId, int kingdomId, string type, Dictionary<string, object> result) { }
        private async Task<Dictionary<string, object>> ProcessCoalitionJointResearch(Dictionary<string, object> coalition, Dictionary<string, object> details, int kingdomId) => new Dictionary<string, object>();
        private async Task<Dictionary<string, object>> ProcessCoalitionTerritoryCoordination(Dictionary<string, object> coalition, Dictionary<string, object> details, int kingdomId) => new Dictionary<string, object>();
        private async Task<Dictionary<string, object>> ProcessCoalitionKvKPreparation(Dictionary<string, object> coalition, Dictionary<string, object> details, int kingdomId) => new Dictionary<string, object>();
        private async Task<Dictionary<string, object>> ProcessCoalitionResourceSharing(Dictionary<string, object> coalition, Dictionary<string, object> details, int kingdomId) => new Dictionary<string, object>();
        private async Task<Dictionary<string, object>> ProcessCoalitionStrategicPlanning(Dictionary<string, object> coalition, Dictionary<string, object> details, int kingdomId) => new Dictionary<string, object>();
        private async Task<Dictionary<string, object>> CalculateAccumulatedCoalitionBenefits(string coalitionId, int kingdomId) => new Dictionary<string, object>();
        private Dictionary<string, object> CalculateAllianceShareOfCoalitionBenefits(Alliance alliance, Dictionary<string, object> benefits, int memberCount) => new Dictionary<string, object>();
        private async Task ApplyDissolutionBenefits(int allianceId, int kingdomId, Dictionary<string, object> benefits) { }
        private async Task MarkCoalitionAsDissolved(string coalitionId, int kingdomId, string reason) { }
        private async Task RestoreAllianceAutonomy(int allianceId, int kingdomId) { }
        private async Task NotifyAllianceOfDissolution(int allianceId, int kingdomId, string reason, Dictionary<string, object> benefits) { }
        private async Task<Dictionary<string, object>> ProcessCoordinatedAttack(Dictionary<string, object> coalition, Dictionary<string, object> details, int kingdomId) => new Dictionary<string, object>();
        private async Task<Dictionary<string, object>> ProcessDefensivePositioning(Dictionary<string, object> coalition, Dictionary<string, object> details, int kingdomId) => new Dictionary<string, object>();
        private async Task<Dictionary<string, object>> ProcessKvKResourcePooling(Dictionary<string, object> coalition, Dictionary<string, object> details, int kingdomId) => new Dictionary<string, object>();

        #endregion

        #region Remaining required interface methods from original implementation

        // Additional stubs for methods called in other sections
        public async Task<(bool Success, string TerritoryId, Dictionary<string, object> DefenseRequirements, Dictionary<string, object> TerritoryBenefits)>
            ClaimTerritoryAsync(int allianceId, int kingdomId, (int X, int Y) territoryCoordinates, string territoryType)
        {
            return (true, $"TERRITORY_{allianceId}_{territoryCoordinates.X}_{territoryCoordinates.Y}",
                    new Dictionary<string, object>(), new Dictionary<string, object>());
        }

        public async Task<(bool Success, DateTime CompletionTime, Dictionary<string, object> AllianceBenefits, Dictionary<int, long> ContributionTracking)>
            ConstructTerritoryBuildingAsync(int allianceId, string territoryId, int kingdomId, string buildingType, Dictionary<int, Dictionary<string, long>> memberContributions)
        {
            return (true, DateTime.UtcNow.AddHours(24), new Dictionary<string, object>(), new Dictionary<int, long>());
        }

        public async Task<Dictionary<string, object>> ManageContestedZoneAsync(int allianceId, string contestedZoneId, int kingdomId, string operationType)
        {
            return new Dictionary<string, object> { ["Success"] = true };
        }

        public async Task<(bool TerritoryRetained, Dictionary<string, object> BanishmentConsequences, Dictionary<string, object> DefenseRewards)>
            ProcessTerritoryDefenseAsync(int allianceId, string territoryId, int kingdomId, Dictionary<string, object> defenseResult)
        {
            return (true, new Dictionary<string, object>(), new Dictionary<string, object>());
        }

        public async Task<(bool Success, int SelectedHostId, Dictionary<string, object> VotingResults, Dictionary<string, object> HostPrivileges)>
            ConductDemocraticHostSelectionAsync(int allianceId, int kingdomId, string kvkEventId, List<int> hostCandidates)
        {
            return (true, hostCandidates.FirstOrDefault(), new Dictionary<string, object>(), new Dictionary<string, object>());
        }

        public async Task<(bool Success, Dictionary<int, string> NewLeadershipRoles, Dictionary<string, object> RolePrivileges)>
            ProcessLeadershipElectionAsync(int allianceId, int kingdomId, string electionType, List<int> candidateIds, Dictionary<int, int> memberVotes)
        {
            return (true, new Dictionary<int, string>(), new Dictionary<string, object>());
        }

        public async Task<(bool Success, string AssignedRole, Dictionary<string, bool> GrantedPermissions)>
            ManageRoleBasedPermissionsAsync(int allianceId, int kingdomId, int playerId, string newRole, Dictionary<string, bool> customPermissions = null)
        {
            return (true, newRole, new Dictionary<string, bool>());
        }

        public async Task<(bool ProposalPassed, double ApprovalPercentage, Dictionary<string, object> ImplementationPlan, List<string> FraudAlerts)>
            ConductAllianceVotingAsync(int allianceId, int kingdomId, string proposalType, Dictionary<string, object> proposalDetails, Dictionary<int, bool> memberVotes)
        {
            return (true, 0.75, new Dictionary<string, object>(), new List<string>());
        }

        public async Task<(bool Success, Dictionary<string, long> NewTreasuryBalance, Dictionary<string, object> AuditEntry)>
            ManageTreasuryOperationAsync(int allianceId, int kingdomId, string operationType, Dictionary<string, long> resourceDetails, int authorizingPlayerId)
        {
            return (true, new Dictionary<string, long>(), new Dictionary<string, object>());
        }

        public async Task<Dictionary<string, object>> ProcessAutomaticContributionsAsync(int allianceId, int kingdomId, string contributionType)
        {
            return new Dictionary<string, object> { ["Success"] = true };
        }

        public async Task<Dictionary<string, object>> DistributeCollectiveBenefitsAsync(int allianceId, int kingdomId, string distributionType, Dictionary<string, object> distributionCriteria)
        {
            return new Dictionary<string, object> { ["Success"] = true };
        }

        #endregion
    }
}