using System;
using System.Collections.Generic;
using NPP.SmartSchedue.Api.Contracts.Services.Integration.Output;

namespace NPP.SmartSchedue.Api.Contracts.Services.Integration.Output
{
    /// <summary>
    /// 处理器执行结果
    /// 用于表示五层决策模型中各层处理器的执行结果
    /// 包含执行状态、性能指标、处理统计等完整信息
    /// </summary>
    public class ProcessorResult
    {
        #region 核心执行状态

        /// <summary>
        /// 处理器执行是否成功
        /// </summary>
        public bool IsSuccess { get; set; }

        /// <summary>
        /// 处理器名称
        /// 用于标识具体的处理器类型，如：QualificationFilter、ConstraintEvaluation等
        /// </summary>
        public string ProcessorName { get; set; } = string.Empty;

        /// <summary>
        /// 执行耗时（毫秒）
        /// 用于性能监控和优化分析
        /// </summary>
        public long ExecutionTimeMs { get; set; }

        /// <summary>
        /// 执行结果消息
        /// 成功或失败的详细描述信息
        /// </summary>
        public string Message { get; set; } = string.Empty;

        #endregion

        #region 处理统计信息

        /// <summary>
        /// 成功处理的数量
        /// 根据处理器类型有不同的含义：
        /// - 资格过滤：资质匹配成功的人员数量
        /// - 约束评估：通过约束检查的人员数量
        /// - 优化决策：完成优化评分的人员数量
        /// - 结果生成：成功分配的任务数量
        /// </summary>
        public int SuccessCount { get; set; }

        /// <summary>
        /// 失败处理的数量
        /// 主要用于结果生成阶段，记录分配失败的任务数量
        /// </summary>
        public int FailureCount { get; set; }

        /// <summary>
        /// 总处理数量
        /// 处理器处理的总体数量，用于计算成功率
        /// </summary>
        public int ProcessedCount { get; set; }

        /// <summary>
        /// 跳过处理的数量
        /// 某些情况下可能需要跳过处理的记录数量
        /// </summary>
        public int SkippedCount { get; set; }

        #endregion

        #region 详细结果数据

        /// <summary>
        /// 处理器返回的结果数据
        /// 根据处理器类型包含不同的数据结构：
        /// - 资格过滤：FilteredCandidates
        /// - 约束评估：ConstraintResults
        /// - 优化决策：OptimizationResults
        /// - 结果生成：AllocationGenerationResult
        /// </summary>
        public object? ResultData { get; set; }

        /// <summary>
        /// 过滤后的候选人列表
        /// 资格过滤处理器的主要输出
        /// </summary>
        public List<PersonnelCandidate>? FilteredCandidates { get; set; }

        /// <summary>
        /// 评估后的候选人列表
        /// 约束评估处理器的主要输出
        /// </summary>
        public List<PersonnelCandidate>? EvaluatedCandidates { get; set; }

        /// <summary>
        /// 排名后的候选人列表
        /// 优化决策处理器的主要输出
        /// </summary>
        public List<PersonnelCandidate>? RankedCandidates { get; set; }

        /// <summary>
        /// 最终分配结果
        /// 结果生成处理器的主要输出
        /// </summary>
        public object? FinalResult { get; set; }

        #endregion

        #region 处理日志和错误信息

        /// <summary>
        /// 处理日志
        /// 记录处理器执行过程中的关键步骤和状态
        /// </summary>
        public string ProcessingLog { get; set; } = string.Empty;

        /// <summary>
        /// 警告信息列表
        /// 处理器执行过程中产生的警告信息
        /// </summary>
        public List<string> Warnings { get; set; } = new();

        /// <summary>
        /// 错误信息列表
        /// 处理器执行过程中产生的错误信息
        /// </summary>
        public List<string> Errors { get; set; } = new();

        #endregion

        #region 性能和质量指标

        /// <summary>
        /// 处理成功率
        /// 计算公式：SuccessCount / ProcessedCount * 100
        /// </summary>
        public double SuccessRate => ProcessedCount > 0 ? (double)SuccessCount / ProcessedCount * 100 : 0;

        /// <summary>
        /// 平均处理时间（毫秒）
        /// 计算公式：ExecutionTimeMs / ProcessedCount
        /// </summary>
        public double AverageProcessingTime => ProcessedCount > 0 ? (double)ExecutionTimeMs / ProcessedCount : 0;

        /// <summary>
        /// 性能评分（0-100）
        /// 基于执行时间和处理数量的综合评分
        /// </summary>
        public double PerformanceScore => CalculatePerformanceScore();

        /// <summary>
        /// 质量评分（0-100）
        /// 基于成功率和错误数量的综合评分
        /// </summary>
        public double QualityScore => CalculateQualityScore();

        #endregion

        #region 扩展属性

        /// <summary>
        /// 处理器版本信息
        /// 用于追踪处理器的版本和更新历史
        /// </summary>
        public string ProcessorVersion { get; set; } = string.Empty;

        /// <summary>
        /// 处理器配置信息
        /// 记录处理器执行时使用的配置参数
        /// </summary>
        public Dictionary<string, object> Configuration { get; set; } = new();

        /// <summary>
        /// 执行环境信息
        /// 记录处理器执行的环境相关信息
        /// </summary>
        public Dictionary<string, object> EnvironmentInfo { get; set; } = new();

        /// <summary>
        /// 创建时间
        /// 处理器结果创建的时间戳
        /// </summary>
        public DateTime CreatedAt { get; set; } = DateTime.UtcNow;

        #endregion

        #region 私有方法

        /// <summary>
        /// 计算性能评分
        /// </summary>
        private double CalculatePerformanceScore()
        {
            if (ProcessedCount == 0) return 0;

            // 基础分数：基于处理数量
            var volumeScore = Math.Min(ProcessedCount * 10, 50);

            // 效率分数：基于平均处理时间
            var efficiencyScore = 0.0;
            if (AverageProcessingTime > 0)
            {
                // 假设理想平均处理时间为10ms，超过则扣分
                var idealTime = 10.0;
                var timeRatio = idealTime / AverageProcessingTime;
                efficiencyScore = Math.Min(timeRatio * 50, 50);
            }

            return volumeScore + efficiencyScore;
        }

        /// <summary>
        /// 计算质量评分
        /// </summary>
        private double CalculateQualityScore()
        {
            var baseScore = SuccessRate;

            // 错误数量扣分
            var errorPenalty = Math.Min(Errors.Count * 5, 20);
            var warningPenalty = Math.Min(Warnings.Count * 2, 10);

            return Math.Max(0, baseScore - errorPenalty - warningPenalty);
        }

        #endregion

        #region 静态工厂方法

        /// <summary>
        /// 创建成功结果
        /// </summary>
        public static ProcessorResult CreateSuccess(string processorName, string message, int successCount, int processedCount, long executionTimeMs)
        {
            return new ProcessorResult
            {
                IsSuccess = true,
                ProcessorName = processorName,
                Message = message,
                SuccessCount = successCount,
                ProcessedCount = processedCount,
                ExecutionTimeMs = executionTimeMs,
                CreatedAt = DateTime.UtcNow
            };
        }

        /// <summary>
        /// 创建失败结果
        /// </summary>
        public static ProcessorResult CreateFailure(string processorName, string message, long executionTimeMs, List<string>? errors = null)
        {
            return new ProcessorResult
            {
                IsSuccess = false,
                ProcessorName = processorName,
                Message = message,
                ExecutionTimeMs = executionTimeMs,
                Errors = errors ?? new List<string>(),
                CreatedAt = DateTime.UtcNow
            };
        }

        /// <summary>
        /// 创建资格过滤结果
        /// </summary>
        public static ProcessorResult CreateQualificationFilterResult(bool isSuccess, int totalProcessed, int totalQualified, long executionTimeMs, string message)
        {
            return new ProcessorResult
            {
                IsSuccess = isSuccess,
                ProcessorName = "QualificationFilter",
                ExecutionTimeMs = executionTimeMs,
                SuccessCount = totalQualified,
                ProcessedCount = totalProcessed,
                Message = message,
                CreatedAt = DateTime.UtcNow
            };
        }

        /// <summary>
        /// 创建约束评估结果
        /// </summary>
        public static ProcessorResult CreateConstraintEvaluationResult(bool isSuccess, int totalEvaluated, int totalPassed, long executionTimeMs, string message)
        {
            return new ProcessorResult
            {
                IsSuccess = isSuccess,
                ProcessorName = "ConstraintEvaluation",
                ExecutionTimeMs = executionTimeMs,
                SuccessCount = totalPassed,
                ProcessedCount = totalEvaluated,
                Message = message,
                CreatedAt = DateTime.UtcNow
            };
        }

        /// <summary>
        /// 创建优化决策结果
        /// </summary>
        public static ProcessorResult CreateOptimizationDecisionResult(bool isSuccess, int totalOptimized, long executionTimeMs, string message)
        {
            return new ProcessorResult
            {
                IsSuccess = isSuccess,
                ProcessorName = "OptimizationDecision",
                ExecutionTimeMs = executionTimeMs,
                SuccessCount = totalOptimized,
                ProcessedCount = totalOptimized,
                Message = message,
                CreatedAt = DateTime.UtcNow
            };
        }

        /// <summary>
        /// 创建结果生成结果
        /// </summary>
        public static ProcessorResult CreateResultGenerationResult(bool isSuccess, int successCount, int failureCount, int totalTasks, long executionTimeMs, string message, object? resultData = null)
        {
            return new ProcessorResult
            {
                IsSuccess = isSuccess,
                ProcessorName = "ResultGeneration",
                ExecutionTimeMs = executionTimeMs,
                SuccessCount = successCount,
                FailureCount = failureCount,
                ProcessedCount = totalTasks,
                Message = message,
                ResultData = resultData,
                CreatedAt = DateTime.UtcNow
            };
        }

        #endregion
    }
}
