/*
 * File: /src/server/ShadowedRealms.Core/Interfaces/Repositories/IAllianceRepository.cs
 * Created: 2025-10-19
 * Last Modified: 2025-10-19
 * Description: Alliance repository interface defining alliance-specific data access operations.
 *              Handles alliance lifecycle, coalition systems, research trees, territory management,
 *              5-tier hierarchy, member management, and democratic leadership systems. Core innovation
 *              is the coalition system that preserves alliance identity during KvK events.
 * Last Edit Notes: Initial implementation with coalition mechanics, research trees, territory systems, and democratic leadership.
 */

using ShadowedRealms.Core.Models;
using ShadowedRealms.Core.Models.Alliance;
using System.Linq.Expressions;

namespace ShadowedRealms.Core.Interfaces.Repositories
{
    /// <summary>
    /// Repository interface for Alliance entity operations, providing comprehensive alliance lifecycle management,
    /// coalition systems, research trees, territory control, democratic leadership, and member coordination.
    /// Core innovation: Coalition system preserves alliance independence during kingdom events.
    /// </summary>
    public interface IAllianceRepository : IRepository<Alliance, int>
    {
        #region Alliance Lifecycle Management

        /// <summary>
        /// Creates a new alliance within the specified kingdom with initial configuration and founder assignment.
        /// Automatically sets up 5-tier leadership hierarchy, research trees, and territory management systems.
        /// </summary>
        /// <param name="allianceName">The name for the new alliance (must be unique within kingdom)</param>
        /// <param name="allianceTag">Short alliance tag (2-5 characters, unique within kingdom)</param>
        /// <param name="founderId">The player who will become the alliance leader</param>
        /// <param name="kingdomId">The kingdom where the alliance will be created</param>
        /// <param name="foundingConfiguration">Initial alliance setup and policies</param>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>The newly created alliance with founder assigned as leader</returns>
        /// <exception cref="ArgumentException">Thrown when name/tag is invalid, taken, or founder is ineligible</exception>
        /// <exception cref="InvalidOperationException">Thrown when alliance creation fails due to system constraints</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task<Alliance> CreateNewAllianceAsync(string allianceName, string allianceTag, int founderId, int kingdomId,
            object foundingConfiguration, CancellationToken cancellationToken = default);

        /// <summary>
        /// Gets an alliance by its unique tag within the specified kingdom context.
        /// Used for alliance lookup, invitation systems, and diplomatic communications.
        /// </summary>
        /// <param name="allianceTag">The alliance tag to search for</param>
        /// <param name="kingdomId">The kingdom context for the search</param>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>The alliance if found within the kingdom, null otherwise</returns>
        /// <exception cref="ArgumentException">Thrown when allianceTag is null/empty or kingdomId is invalid</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task<Alliance?> GetAllianceByTagAsync(string allianceTag, int kingdomId,
            CancellationToken cancellationToken = default);

        /// <summary>
        /// Disbands an alliance, handling member redistribution, resource transfers, and historical data preservation.
        /// Manages coalition withdrawals, territory releases, and research tree preservation for members.
        /// </summary>
        /// <param name="allianceId">The alliance to disband</param>
        /// <param name="kingdomId">The kingdom context for the operation</param>
        /// <param name="disbandReason">Reason for disbanding (for historical records)</param>
        /// <param name="authorizingPlayerId">The leader authorizing the disbandment</param>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>True if alliance was successfully disbanded</returns>
        /// <exception cref="ArgumentException">Thrown when parameters are invalid or player lacks authority</exception>
        /// <exception cref="InvalidOperationException">Thrown when alliance cannot be disbanded due to active commitments</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task<bool> DisbandAllianceAsync(int allianceId, int kingdomId, string disbandReason, int authorizingPlayerId,
            CancellationToken cancellationToken = default);

        /// <summary>
        /// Archives an inactive alliance while preserving historical data and member contribution records.
        /// Used for alliances that no longer have active leadership or sufficient membership.
        /// </summary>
        /// <param name="allianceId">The alliance to archive</param>
        /// <param name="kingdomId">The kingdom context for the operation</param>
        /// <param name="archiveReason">Reason for archiving (inactivity, merger, etc.)</param>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>True if alliance was archived successfully</returns>
        /// <exception cref="ArgumentException">Thrown when parameters are invalid</exception>
        /// <exception cref="InvalidOperationException">Thrown when alliance has active members or commitments</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task<bool> ArchiveAllianceAsync(int allianceId, int kingdomId, string archiveReason,
            CancellationToken cancellationToken = default);

        #endregion

        #region Coalition System (Core Innovation)

        /// <summary>
        /// Creates a coalition between multiple alliances for KvK events while preserving individual alliance identities.
        /// CORE INNOVATION: Allows cross-alliance cooperation without forced merging or identity loss.
        /// </summary>
        /// <param name="participatingAllianceIds">Alliances joining the coalition</param>
        /// <param name="coalitionName">Name for the temporary coalition</param>
        /// <param name="eventType">Type of event requiring coalition (KvK, territory war, etc.)</param>
        /// <param name="kingdomId">The kingdom context for the operation</param>
        /// <param name="coalitionConfiguration">Coalition leadership structure and resource sharing rules</param>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>The created coalition with participating alliances</returns>
        /// <exception cref="ArgumentException">Thrown when parameters are invalid or alliances are ineligible</exception>
        /// <exception cref="InvalidOperationException">Thrown when coalition creation fails due to conflicts</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task<object> CreateCoalitionAsync(IEnumerable<int> participatingAllianceIds, string coalitionName,
            string eventType, int kingdomId, object coalitionConfiguration, CancellationToken cancellationToken = default);

        /// <summary>
        /// Gets alliances that are eligible for coalition participation based on compatibility metrics,
        /// leadership activity, member engagement, and strategic alignment assessment.
        /// </summary>
        /// <param name="initiatingAllianceId">The alliance seeking coalition partners</param>
        /// <param name="eventType">The type of event requiring coalition</param>
        /// <param name="kingdomId">The kingdom context for the search</param>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>Compatible alliances with compatibility scores and synergy analysis</returns>
        /// <exception cref="ArgumentException">Thrown when parameters are invalid</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task<IEnumerable<(Alliance Alliance, double CompatibilityScore, string[] SynergyAreas)>> GetCoalitionEligibleAlliancesAsync(
            int initiatingAllianceId, string eventType, int kingdomId, CancellationToken cancellationToken = default);

        /// <summary>
        /// Updates coalition participation status for an alliance, handling role assignments, resource contributions,
        /// and coordination responsibilities while maintaining alliance independence.
        /// </summary>
        /// <param name="allianceId">The alliance updating coalition status</param>
        /// <param name="coalitionId">The coalition being joined or left (null to leave all coalitions)</param>
        /// <param name="participationRole">Role within the coalition (coordinator, support, specialist, etc.)</param>
        /// <param name="kingdomId">The kingdom context for the operation</param>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>Updated alliance with new coalition status</returns>
        /// <exception cref="ArgumentException">Thrown when parameters are invalid or role assignment fails</exception>
        /// <exception cref="InvalidOperationException">Thrown when coalition change violates agreements</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task<Alliance> UpdateCoalitionParticipationAsync(int allianceId, int? coalitionId, string? participationRole,
            int kingdomId, CancellationToken cancellationToken = default);

        /// <summary>
        /// Gets coalition performance metrics for participating alliances including contribution levels,
        /// coordination effectiveness, and individual alliance achievements within coalition context.
        /// </summary>
        /// <param name="coalitionId">The coalition to analyze</param>
        /// <param name="kingdomId">The kingdom context for the operation</param>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>Coalition performance breakdown by participating alliance</returns>
        /// <exception cref="ArgumentException">Thrown when parameters are invalid</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task<object> GetCoalitionPerformanceMetricsAsync(int coalitionId, int kingdomId,
            CancellationToken cancellationToken = default);

        /// <summary>
        /// Dissolves a coalition while preserving individual alliance achievements and returning control
        /// to individual alliance leadership. Handles resource redistribution and historical record keeping.
        /// </summary>
        /// <param name="coalitionId">The coalition to dissolve</param>
        /// <param name="kingdomId">The kingdom context for the operation</param>
        /// <param name="dissolutionReason">Reason for coalition dissolution</param>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>Updated participating alliances with individual control restored</returns>
        /// <exception cref="ArgumentException">Thrown when parameters are invalid</exception>
        /// <exception cref="InvalidOperationException">Thrown when coalition cannot be dissolved due to active commitments</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task<IEnumerable<Alliance>> DissolveCoalitionAsync(int coalitionId, int kingdomId, string dissolutionReason,
            CancellationToken cancellationToken = default);

        #endregion

        #region Research Tree System

        /// <summary>
        /// Updates alliance research progress in specific technology areas, validating prerequisites,
        /// resource costs, and member contribution requirements. Handles Military, Economic, and Technology branches.
        /// </summary>
        /// <param name="allianceId">The alliance conducting research</param>
        /// <param name="researchArea">The research area being advanced (Military, Economic, Technology)</param>
        /// <param name="researchLevel">The target research level</param>
        /// <param name="contributingMembers">Members contributing resources to the research</param>
        /// <param name="kingdomId">The kingdom context for the operation</param>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>Updated alliance with new research level and unlocked bonuses</returns>
        /// <exception cref="ArgumentException">Thrown when parameters are invalid or research violates prerequisites</exception>
        /// <exception cref="InvalidOperationException">Thrown when alliance lacks resources or member contributions</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task<Alliance> UpdateAllianceResearchAsync(int allianceId, string researchArea, int researchLevel,
            Dictionary<int, object> contributingMembers, int kingdomId, CancellationToken cancellationToken = default);

        /// <summary>
        /// Gets alliances by research specialization for coalition formation, diplomatic relations,
        /// and strategic partnership identification. Matches alliances with complementary research focuses.
        /// </summary>
        /// <param name="kingdomId">The kingdom to search within</param>
        /// <param name="researchCriteria">Minimum research levels in specific areas</param>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>Alliances meeting the research specialization criteria</returns>
        /// <exception cref="ArgumentException">Thrown when parameters are invalid</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task<IEnumerable<Alliance>> GetAlliancesByResearchSpecializationAsync(int kingdomId,
            Dictionary<string, int> researchCriteria, CancellationToken cancellationToken = default);

        /// <summary>
        /// Calculates total research bonuses available to alliance members including base alliance research,
        /// coalition bonuses, and member contribution rewards. Used for individual player bonus calculations.
        /// </summary>
        /// <param name="allianceId">The alliance to calculate bonuses for</param>
        /// <param name="kingdomId">The kingdom context for the operation</param>
        /// <param name="includeCoalitionBonuses">Whether to include bonuses from coalition participation</param>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>Comprehensive breakdown of all research bonuses available to members</returns>
        /// <exception cref="ArgumentException">Thrown when parameters are invalid</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task<object> CalculateAllianceResearchBonusesAsync(int allianceId, int kingdomId, bool includeCoalitionBonuses = true,
            CancellationToken cancellationToken = default);

        /// <summary>
        /// Records member contributions to alliance research including resources, time, and expertise.
        /// Tracks individual contribution metrics for reward distribution and leadership evaluation.
        /// </summary>
        /// <param name="allianceId">The alliance receiving contributions</param>
        /// <param name="memberId">The member making the contribution</param>
        /// <param name="contributionDetails">Resources, time, or expertise contributed</param>
        /// <param name="kingdomId">The kingdom context for the operation</param>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>Updated alliance with recorded contribution and member recognition</returns>
        /// <exception cref="ArgumentException">Thrown when parameters are invalid or member is not in alliance</exception>
        /// <exception cref="InvalidOperationException">Thrown when contribution cannot be processed</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task<Alliance> RecordResearchContributionAsync(int allianceId, int memberId, object contributionDetails,
            int kingdomId, CancellationToken cancellationToken = default);

        #endregion

        #region Territory Management

        /// <summary>
        /// Claims territory for an alliance, validating adjacency requirements, resource costs, and capacity limits.
        /// Handles contested zones, proximity to other alliances, and strategic resource locations.
        /// </summary>
        /// <param name="allianceId">The alliance claiming territory</param>
        /// <param name="territoryCoordinates">The coordinates of the territory to claim</param>
        /// <param name="territoryType">Type of territory (standard, resource, strategic)</param>
        /// <param name="kingdomId">The kingdom context for the operation</param>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>Updated alliance with new territory claim</returns>
        /// <exception cref="ArgumentException">Thrown when parameters are invalid or territory cannot be claimed</exception>
        /// <exception cref="InvalidOperationException">Thrown when alliance lacks requirements for territory claim</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task<Alliance> ClaimTerritoryAsync(int allianceId, (int X, int Y) territoryCoordinates, string territoryType,
            int kingdomId, CancellationToken cancellationToken = default);

        /// <summary>
        /// Upgrades alliance territory buildings including resource generation facilities, defensive structures,
        /// and member benefit buildings. Validates construction prerequisites and resource costs.
        /// </summary>
        /// <param name="allianceId">The alliance upgrading territory</param>
        /// <param name="territoryId">The specific territory being upgraded</param>
        /// <param name="buildingUpgrades">Dictionary of building types and target levels</param>
        /// <param name="kingdomId">The kingdom context for the operation</param>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>Updated alliance with upgraded territory buildings</returns>
        /// <exception cref="ArgumentException">Thrown when parameters are invalid or upgrades violate rules</exception>
        /// <exception cref="InvalidOperationException">Thrown when alliance lacks resources for upgrades</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task<Alliance> UpgradeTerritoryBuildingsAsync(int allianceId, int territoryId, Dictionary<string, int> buildingUpgrades,
            int kingdomId, CancellationToken cancellationToken = default);

        /// <summary>
        /// Gets alliances with territory in contested zones around strategic forest areas and resource locations.
        /// Used for KvK planning, territorial conflicts, and strategic resource competition analysis.
        /// </summary>
        /// <param name="contestedZoneCoordinates">The contested zone to analyze</param>
        /// <param name="kingdomId">The kingdom context for the search</param>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>Alliances with territorial claims in the contested zone</returns>
        /// <exception cref="ArgumentException">Thrown when parameters are invalid</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task<IEnumerable<(Alliance Alliance, object TerritoryDetails)>> GetAlliancesInContestedZoneAsync(
            (int X, int Y) contestedZoneCoordinates, int kingdomId, CancellationToken cancellationToken = default);

        /// <summary>
        /// Calculates territory control bonuses for alliance members including resource generation,
        /// defensive advantages, and strategic positioning benefits.
        /// </summary>
        /// <param name="allianceId">The alliance to calculate bonuses for</param>
        /// <param name="kingdomId">The kingdom context for the operation</param>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>Comprehensive territory bonus breakdown for alliance members</returns>
        /// <exception cref="ArgumentException">Thrown when parameters are invalid</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task<object> CalculateTerritoryBonusesAsync(int allianceId, int kingdomId,
            CancellationToken cancellationToken = default);

        /// <summary>
        /// Releases alliance territory claims, handling resource redistribution and member notification.
        /// Can be voluntary (strategic repositioning) or forced (insufficient maintenance/defense).
        /// </summary>
        /// <param name="allianceId">The alliance releasing territory</param>
        /// <param name="territoryIds">Specific territories to release (empty for all territory)</param>
        /// <param name="releaseReason">Reason for territory release</param>
        /// <param name="kingdomId">The kingdom context for the operation</param>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>Updated alliance with released territories</returns>
        /// <exception cref="ArgumentException">Thrown when parameters are invalid</exception>
        /// <exception cref="InvalidOperationException">Thrown when territory release fails due to active conflicts</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task<Alliance> ReleaseTerritoryAsync(int allianceId, IEnumerable<int>? territoryIds, string releaseReason,
            int kingdomId, CancellationToken cancellationToken = default);

        #endregion

        #region 5-Tier Leadership Hierarchy

        /// <summary>
        /// Updates alliance leadership structure using the 5-tier hierarchy system with role-based permissions.
        /// Handles Leader, Co-Leaders, Generals, Captains, and Members with appropriate authority delegation.
        /// </summary>
        /// <param name="allianceId">The alliance updating leadership</param>
        /// <param name="leadershipChanges">Dictionary of member IDs and new roles</param>
        /// <param name="authorizingPlayerId">The current leader authorizing changes</param>
        /// <param name="kingdomId">The kingdom context for the operation</param>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>Updated alliance with new leadership structure</returns>
        /// <exception cref="ArgumentException">Thrown when parameters are invalid or player lacks authority</exception>
        /// <exception cref="InvalidOperationException">Thrown when leadership changes violate hierarchy rules</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task<Alliance> UpdateLeadershipHierarchyAsync(int allianceId, Dictionary<int, string> leadershipChanges,
            int authorizingPlayerId, int kingdomId, CancellationToken cancellationToken = default);

        /// <summary>
        /// Gets alliance leadership structure with role assignments, permissions, and activity status.
        /// Provides complete hierarchy visualization for member management and authority tracking.
        /// </summary>
        /// <param name="allianceId">The alliance to get leadership for</param>
        /// <param name="kingdomId">The kingdom context for the operation</param>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>Complete leadership hierarchy with roles and permissions</returns>
        /// <exception cref="ArgumentException">Thrown when parameters are invalid</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task<object> GetAllianceLeadershipAsync(int allianceId, int kingdomId,
            CancellationToken cancellationToken = default);

        /// <summary>
        /// Validates leadership action permissions based on role hierarchy and specific operation requirements.
        /// Prevents unauthorized actions while supporting delegated authority within the alliance structure.
        /// </summary>
        /// <param name="allianceId">The alliance context for validation</param>
        /// <param name="playerId">The player attempting the action</param>
        /// <param name="actionType">The type of action being attempted</param>
        /// <param name="kingdomId">The kingdom context for validation</param>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>Permission validation result with authority level and restrictions</returns>
        /// <exception cref="ArgumentException">Thrown when parameters are invalid</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task<(bool IsAuthorized, string AuthorityLevel, string[] Restrictions)> ValidateLeadershipActionAsync(
            int allianceId, int playerId, string actionType, int kingdomId, CancellationToken cancellationToken = default);

        /// <summary>
        /// Initiates democratic leadership transition within the alliance, setting up voting systems
        /// and succession planning for leadership changes and emergency leadership transfer.
        /// </summary>
        /// <param name="allianceId">The alliance conducting leadership transition</param>
        /// <param name="transitionType">Type of transition (election, succession, emergency)</param>
        /// <param name="candidateIds">Eligible candidates for leadership positions</param>
        /// <param name="kingdomId">The kingdom context for the operation</param>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>Leadership transition configuration with voting setup</returns>
        /// <exception cref="ArgumentException">Thrown when parameters are invalid or candidates are ineligible</exception>
        /// <exception cref="InvalidOperationException">Thrown when transition cannot be initiated</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task<object> InitiateLeadershipTransitionAsync(int allianceId, string transitionType, IEnumerable<int> candidateIds,
            int kingdomId, CancellationToken cancellationToken = default);

        #endregion

        #region Member Management

        /// <summary>
        /// Processes member applications to join the alliance, validating eligibility requirements,
        /// cooldown periods, and alliance capacity limits. Handles both applications and invitations.
        /// </summary>
        /// <param name="allianceId">The alliance receiving the application</param>
        /// <param name="applicantId">The player applying to join</param>
        /// <param name="applicationMethod">Application or invitation</param>
        /// <param name="kingdomId">The kingdom context for the operation</param>
        /// <param name="sponsoringMemberId">Member sponsoring the application (if applicable)</param>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>Application result with status and next steps</returns>
        /// <exception cref="ArgumentException">Thrown when parameters are invalid or applicant is ineligible</exception>
        /// <exception cref="InvalidOperationException">Thrown when application cannot be processed</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task<object> ProcessMemberApplicationAsync(int allianceId, int applicantId, string applicationMethod,
            int kingdomId, int? sponsoringMemberId = null, CancellationToken cancellationToken = default);

        /// <summary>
        /// Removes a member from the alliance, handling voluntary departures, kicks, and disciplinary actions.
        /// Manages resource contribution settlements, role transitions, and exit procedures.
        /// </summary>
        /// <param name="allianceId">The alliance losing the member</param>
        /// <param name="memberId">The member being removed</param>
        /// <param name="removalType">Voluntary departure, kick, or disciplinary action</param>
        /// <param name="authorizingPlayerId">The leader authorizing the removal (for kicks)</param>
        /// <param name="kingdomId">The kingdom context for the operation</param>
        /// <param name="removalReason">Reason for removal (for record keeping)</param>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>Updated alliance with member removed and resources settled</returns>
        /// <exception cref="ArgumentException">Thrown when parameters are invalid or player lacks authority</exception>
        /// <exception cref="InvalidOperationException">Thrown when member removal violates alliance policies</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task<Alliance> RemoveMemberAsync(int allianceId, int memberId, string removalType, int kingdomId,
            int? authorizingPlayerId = null, string? removalReason = null, CancellationToken cancellationToken = default);

        /// <summary>
        /// Updates member contribution tracking including research donations, territory support,
        /// military assistance, and social engagement metrics for recognition and reward systems.
        /// </summary>
        /// <param name="allianceId">The alliance tracking contributions</param>
        /// <param name="memberId">The member making contributions</param>
        /// <param name="contributionData">Detailed contribution information</param>
        /// <param name="kingdomId">The kingdom context for the operation</param>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>Updated alliance with recorded member contributions</returns>
        /// <exception cref="ArgumentException">Thrown when parameters are invalid or member is not in alliance</exception>
        /// <exception cref="InvalidOperationException">Thrown when contribution tracking fails</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task<Alliance> UpdateMemberContributionsAsync(int allianceId, int memberId, object contributionData,
            int kingdomId, CancellationToken cancellationToken = default);

        /// <summary>
        /// Gets member performance analytics for alliance management including activity levels,
        /// contribution history, leadership potential, and social engagement metrics.
        /// </summary>
        /// <param name="allianceId">The alliance to analyze members for</param>
        /// <param name="analysisType">Type of analysis (performance, potential, engagement)</param>
        /// <param name="kingdomId">The kingdom context for the operation</param>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>Member analytics with performance rankings and development recommendations</returns>
        /// <exception cref="ArgumentException">Thrown when parameters are invalid</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task<object> GetMemberPerformanceAnalyticsAsync(int allianceId, string analysisType, int kingdomId,
            CancellationToken cancellationToken = default);

        #endregion

        #region Resource and Economic Management

        /// <summary>
        /// Manages alliance treasury including member contributions, resource allocation, and emergency reserves.
        /// Handles collective resource pooling for research, territory maintenance, and member assistance.
        /// </summary>
        /// <param name="allianceId">The alliance managing treasury</param>
        /// <param name="treasuryTransaction">Resource deposits, withdrawals, or allocations</param>
        /// <param name="authorizingPlayerId">The leader authorizing the transaction</param>
        /// <param name="kingdomId">The kingdom context for the operation</param>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>Updated alliance with new treasury status</returns>
        /// <exception cref="ArgumentException">Thrown when parameters are invalid or player lacks authority</exception>
        /// <exception cref="InvalidOperationException">Thrown when treasury transaction violates policies</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task<Alliance> ManageAllianceTreasuryAsync(int allianceId, object treasuryTransaction, int authorizingPlayerId,
            int kingdomId, CancellationToken cancellationToken = default);

        /// <summary>
        /// Facilitates resource sharing between alliance members including loans, gifts, and emergency assistance.
        /// Tracks member-to-member resource transfers and alliance-sponsored support programs.
        /// </summary>
        /// <param name="allianceId">The alliance facilitating resource sharing</param>
        /// <param name="senderId">The member providing resources</param>
        /// <param name="recipientId">The member receiving resources</param>
        /// <param name="resourceTransfer">Resources being transferred</param>
        /// <param name="transferType">Gift, loan, or emergency assistance</param>
        /// <param name="kingdomId">The kingdom context for the operation</param>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>Updated alliance with recorded resource transfer</returns>
        /// <exception cref="ArgumentException">Thrown when parameters are invalid or members are ineligible</exception>
        /// <exception cref="InvalidOperationException">Thrown when resource transfer violates policies</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task<Alliance> FacilitateResourceSharingAsync(int allianceId, int senderId, int recipientId,
            object resourceTransfer, string transferType, int kingdomId, CancellationToken cancellationToken = default);

        /// <summary>
        /// Gets alliance economic analytics including resource generation efficiency, member contribution patterns,
        /// treasury health, and economic competitiveness compared to other alliances.
        /// </summary>
        /// <param name="allianceId">The alliance to analyze</param>
        /// <param name="analysisTimeframe">Time period for economic analysis</param>
        /// <param name="kingdomId">The kingdom context for the operation</param>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>Comprehensive economic analysis with trends and recommendations</returns>
        /// <exception cref="ArgumentException">Thrown when parameters are invalid</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task<object> GetAllianceEconomicAnalyticsAsync(int allianceId, TimeSpan analysisTimeframe, int kingdomId,
            CancellationToken cancellationToken = default);

        #endregion

        #region Alliance Analytics and Performance

        /// <summary>
        /// Gets comprehensive alliance performance metrics including member satisfaction, military effectiveness,
        /// economic efficiency, territorial control, and social engagement for leadership analysis.
        /// </summary>
        /// <param name="allianceId">The alliance to analyze</param>
        /// <param name="kingdomId">The kingdom context for the operation</param>
        /// <param name="analysisDepth">Surface-level, detailed, or comprehensive analysis</param>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>Detailed alliance performance analytics with actionable insights</returns>
        /// <exception cref="ArgumentException">Thrown when parameters are invalid</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task<object> GetAlliancePerformanceMetricsAsync(int allianceId, int kingdomId, string analysisDepth = "detailed",
            CancellationToken cancellationToken = default);

        /// <summary>
        /// Gets alliance ranking and competitive position within the kingdom including power rankings,
        /// territorial control, research advancement, and member satisfaction benchmarks.
        /// </summary>
        /// <param name="kingdomId">The kingdom to generate rankings for</param>
        /// <param name="rankingCategory">The metric to rank by (power, territory, research, satisfaction)</param>
        /// <param name="topCount">Number of top alliances to return</param>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>Alliance rankings with detailed competitive analysis</returns>
        /// <exception cref="ArgumentException">Thrown when parameters are invalid</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task<IEnumerable<(Alliance Alliance, object RankingValue, int Rank, object CompetitiveAnalysis)>> GetAllianceRankingsAsync(
            int kingdomId, string rankingCategory, int topCount = 50, CancellationToken cancellationToken = default);

        /// <summary>
        /// Generates alliance health report identifying potential issues like leadership conflicts,
        /// member dissatisfaction, resource shortages, or strategic vulnerabilities requiring attention.
        /// </summary>
        /// <param name="allianceId">The alliance to assess</param>
        /// <param name="kingdomId">The kingdom context for the operation</param>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>Alliance health assessment with priority action items</returns>
        /// <exception cref="ArgumentException">Thrown when parameters are invalid</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task<object> GenerateAllianceHealthReportAsync(int allianceId, int kingdomId,
            CancellationToken cancellationToken = default);

        #endregion

        #region Democratic Host Selection for KvK

        /// <summary>
        /// Initiates democratic host selection process for KvK events where alliance members vote
        /// for leadership roles during kingdom events. Ensures fair representation and member engagement.
        /// </summary>
        /// <param name="allianceId">The alliance participating in host selection</param>
        /// <param name="kvkEventId">The KvK event requiring host selection</param>
        /// <param name="availableRoles">Leadership roles available during the event</param>
        /// <param name="kingdomId">The kingdom context for the operation</param>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>Host selection voting configuration with candidate nominations</returns>
        /// <exception cref="ArgumentException">Thrown when parameters are invalid or alliance not eligible</exception>
        /// <exception cref="InvalidOperationException">Thrown when host selection cannot be initiated</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task<object> InitiateKvKHostSelectionAsync(int allianceId, int kvkEventId, IEnumerable<string> availableRoles,
            int kingdomId, CancellationToken cancellationToken = default);

        /// <summary>
        /// Processes votes for alliance representatives in KvK host selection, ensuring democratic
        /// participation and transparent selection of alliance members for kingdom leadership roles.
        /// </summary>
        /// <param name="allianceId">The alliance conducting voting</param>
        /// <param name="votingMemberId">The member casting their vote</param>
        /// <param name="voteConfiguration">Vote selections for available roles</param>
        /// <param name="kingdomId">The kingdom context for the operation</param>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>Updated voting status with member participation tracking</returns>
        /// <exception cref="ArgumentException">Thrown when parameters are invalid or member ineligible to vote</exception>
        /// <exception cref="InvalidOperationException">Thrown when voting fails due to timing or eligibility</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task<object> ProcessKvKHostVoteAsync(int allianceId, int votingMemberId, object voteConfiguration,
            int kingdomId, CancellationToken cancellationToken = default);

        /// <summary>
        /// Finalizes KvK host selection results, appointing alliance representatives to kingdom roles
        /// and establishing authority delegation for the duration of the KvK event.
        /// </summary>
        /// <param name="allianceId">The alliance finalizing host selection</param>
        /// <param name="selectionResults">Voting results and selected representatives</param>
        /// <param name="kingdomId">The kingdom context for the operation</param>
        /// <param name="cancellationToken">Cancellation token for async operation</param>
        /// <returns>Updated alliance with appointed KvK representatives and authority delegation</returns>
        /// <exception cref="ArgumentException">Thrown when parameters are invalid or results are contested</exception>
        /// <exception cref="InvalidOperationException">Thrown when host selection finalization fails</exception>
        /// <exception cref="OperationCanceledException">Thrown when operation is cancelled</exception>
        Task<Alliance> FinalizeKvKHostSelectionAsync(int allianceId, object selectionResults, int kingdomId,
            CancellationToken cancellationToken = default);

        #endregion
    }
}